在Vue中span标签的背景图是根据后台返回的数据动态显示的图片
在Vue中span标签的背景图是根据后台返回的数据动态显示的图片,如下图中的的红圈是根据后台返回的数据动态显示的图片,对应的HTML是.icon元素实现元素的背景图的动态显示的具体操作如下1)根据后台返回的数据,在该组件的.vue文件中的<script>中的输出对象中使用生命周期钩子created(),在里面定义mapClass数组对象,里面元素的值一一对应后台返回的数
在Vue中span标签的背景图是根据后台返回的数据动态显示的图片,如下图中的的红圈是根据后台返回的数据动态显示的图片,对应的HTML是.icon元素
实现元素的背景图的动态显示的具体操作如下
1)根据后台返回的数据,在该组件的.vue文件中的<script>中的输出对象中使用生命周期钩子created(),在里面定义mapClass数组对象,里面元素的值一一对应后台返回的数据,例如后台返回的数据如下所示:
{
"seller": {
"name": "粥品香坊(回龙观)",
"description": "蜂鸟专送",
"deliveryTime": 38,
"score": 4.2,
"serviceScore": 4.1,
"foodScore": 4.3,
"rankRate": 69.2,
"minPrice": 20,
"deliveryPrice": 4,
"ratingCount": 24,
"sellCount": 90,
"bulletin": "粥品香坊其烹饪粥料的秘方源于中国千年古法,在融和现代制作工艺,由世界烹饪大师屈浩先生领衔研发。坚守纯天然、0添加的良心品质深得消费者青睐,发展至今成为粥类的引领品牌。是2008年奥运会和2013年园博会指定餐饮服务商。",
"supports": [
{
"type": 0,
"description": "在线支付满28减5"
},
{
"type": 1,
"description": "VC无限橙果汁全场8折"
},
{
"type": 2,
"description": "单人精彩套餐"
},
{
"type": 3,
"description": "该商家支持发票,请下单写好发票抬头"
},
{
"type": 4,
"description": "已加入“外卖保”计划,食品安全保障"
}
]
}
}
.icon元素中的背景图对应数据中的supports对象中的type的类型,type---0,1,2,3,4一一对应decrease,discount,special,invoice,guarantee,也就是要显示的图片的名字,其中图片素材如下所示,这就是要在.icon中显示的背景的图片
classMap的定义如下所示:
<script>
export default {
//子组件属性seller的声明
props:{ //子组件通过props属性,获取父组件传递过来的数据
seller:{
type:Object
}
},
//在这个组件created的时候自定义一个classMap属性
created(){
this.classMap = ['decrease','discount','special','invoice','guarantee'];
}
}
</script>
2)在组件的html标签中引用自定义属性classMap,如下所示:
<div class="support" v-if="seller.supports">
<span class="icon" :class="classMap[seller.supports[0].type]"></span>
<span class="text">{{seller.supports[0].description}}</span>
</div>
seller.supports[0].type是后台返回的数据,对照1)中后台返回的supports数组中的第一个元素的type:0,classMap[0]对应的是decrease
3)在组件的<style>标签中给.icon元素定义不同背景
.icon
display: inline-block
width:12px
height:12px
margin-right :4px
background-size:12px 12px
background-repeat :no-repeat
&.decrease
bg-image('decrease_1')
&.discount
bg-image('discount_1')
&.guarantee
bg-image('guarantee_1')
&.invoice
bg-image('invoice_1')
&.special
bg-special('special_1')
其中bg-image()方法是用stylus的mixin特性封装的一个方法,作用是根据不同的设备像素比引用不同的图片,其在mixin.styl文件中的定义如下:根据不同的设备像素比来设置background-image的url,$url是传进来的图片名,然后跟后面的字符串拼接成完整的图片名
bg-image($url)
background-image :url($url+'@2x.png')
@media (-webkit-min-device-pixel-ratio:3),(device-pixel-ratio:3)
background-image :url($url+'@3x.png')
通过以上的设置,就可以根据后台返回的数据,动态的显示icon元素的背景图了
更多推荐
所有评论(0)