组件化icon,来实现根据传入数据不同而显示不同图标代码。
程序员文章站
2022-03-31 22:37:50
...
目标:把classMap显示不同的icon功能抽象成一个组件。
分析:需要传入的参数有icon尺寸,icon种类。所以下面icon.vue里面定义了2个参数size和type,由父组件传入。
难点:css代码层叠关系这里要理清。另外vue中绑定2个class属性可以使用数组形式——:class=”[iconSize,iconType]”,如果不加数组的中括号,会导致只有第一个class类生效。
header.vue中的代码
<template>
<icon :size="1" :type="seller.supports[0].type"></icon>
<li class="support-item" v-for="(item,index) of seller.supports" :key="index">
<icon :size="1" :type="seller.supports[index].type" class="icon"></icon>
<span class="text">{{seller.supports[index].description}}</span>
</li>
</template>
<script type='text/ecmascript-6'>
import icon from '../support-icon/icon'
components: {
star, // ES6缩写,实际为'star': star
icon // ES6缩写,实际为'icon': icon
},
</script>
icon.vue中的代码
<!-- icon.vue代码 -->
<template>
<span class="icon" :class="[iconSize,iconType]"></span>
</template>
<script type='text/ecmascript-6'>
export default {
props: {
size: { // size从父组件header里面传入,决定尺寸
type: Number
},
type: { // score从父组件header里面传入,决定星星数量
type: Number
}
},
data () {
return {
}
},
created () {
this.classMap = ['decrease', 'discount', 'special', 'invoice', 'guarantee']
},
components: {},
computed: {
iconSize () {
return 'icon-' + this.size // 返回iconSize的值,表示不同尺寸下的icon类。使得icon类与size相关联。
},
iconType () {
let result = ''
result = this.classMap[this.type]
return result
}
},
methods: {}
}
</script>
<style lang='stylus' rel='stylesheet/stylus'>
@import '../../common/stylus/mixin.styl'
.icon
display: inline-block
vertical-align: top
background-repeat: no-repeat
&.icon-1
width: 12px
height: 12px
background-size: 12px 12px
&.decrease
bg-image('decrease_1')
&.discount
bg-image('discount_1')
&.guarantee
bg-image('guarantee_1')
&.invoice
bg-image('invoice_1')
&.special
bg-image('special_1')
&.icon-2
width: 16px
height: 16px
background-size: 16px 16px
&.decrease
bg-image('decrease_2')
&.discount
bg-image('discount_2')
&.guarantee
bg-image('guarantee_2')
&.invoice
bg-image('invoice_2')
&.special
bg-image('special_2')
&.icon-3
width: 12px
height: 12px
background-size: 12px 12px
&.decrease
bg-image('decrease_3')
&.discount
bg-image('discount_3')
&.guarantee
bg-image('guarantee_3')
&.invoice
bg-image('invoice_3')
&.special
bg-image('special_3')
&.icon-4
width: 16px
height: 16px
background-size: 16px 16px
&.decrease
bg-image('decrease_4')
&.discount
bg-image('discount_4')
&.guarantee
bg-image('guarantee_4')
&.invoice
bg-image('invoice_4')
&.special
bg-image('special_4')
</style>
图标还是和icon.vue放一个目录就近维护。
上一篇: 一次使用iconfont的记录