組件化icon,來實現根據傳入數據不同而顯示不同圖標代碼。

目標:把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放一個目錄就近維護。

這裏寫圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章