我们客服系统的消息列表中,会有产品卡片展示,这个是怎么实现的呢
产品信息其实就是下面这个字符串
product[{"title":"纯坚果零食大礼包一整箱干果类网红爆款解馋小吃休闲食品送女友","price":"¥9.9","img":"https://img.alicdn.com/bao/uploaded/i1/2201453915278/O1CN01dZolFu1orN8dFeKAj_!!0-item_pic.jpg_200x200q90.jpg_.webp","url":"https://www.taobao.com"}]
只需要把上面的字符串解析成html格式就可以了
//转换产品卡片 function replaceProduct(str){ return str.replace(/product\[([^\[\]]+?)\]/g, function (product) { console.log(str,arguments); if(!arguments[1]){ return; } let jsonStr=arguments[1].replace(/\'/g,'"'); try{ let info=JSON.parse(jsonStr); if(typeof info=="undefined"){ return; } if(!info.title) info.title="智能客服系统产品卡片"; if(!info.price) info.price="¥0"; if(info.img){ info.img="<img src='"+info.img+"'/>"; }else{ info.img=""; } if(!info.url) info.url="/"; let html= ` <a class="productCard" href="`+info.url+`" target="_blank"/> `+info.img+` <div class="productCardTitle"> <p class="productCardTitle">`+info.title+`</p> <p class="productCardPrice">`+info.price+`</p> </div> </a> `; return html; }catch (e) { return jsonStr; } }); }
然后给转换后的html增加相应的样式
.productCard{ cursor: pointer; background: #fff; padding: 5px; border-radius: 2px; width: auto; max-width: 730px; display: flex; border-radius: 5px; } .productCard img{ width: 100px; height: 100px; margin-right: 15px; } .productCard .productCardPrice{ color: #ff7736; font-weight: bold; font-size: 16px; margin-top: 10px; } .productCard .productCardTitle{ color: #333; }标签:info,vue,return,卡片,img,title,js,正则,productCard From: https://www.cnblogs.com/taoshihan/p/17091266.html