[美团 可配置的图标组件] vue自定义可配置图标组件

459 阅读1分钟

效果图:

接下来, 我们会围绕组件的 几个点展开讨论:

如何添加icon对象库

技术点讲解:

1.如何添加icon对象库

// iconType 固定搭配
export const iconType = {
  // 组织
  organization: {
    // icon
    icon: 'icon-zuzhi',
    // 名字
    title: '组织'
  // KPI
  kpi: {
    // icon
    icon: 'icon-KPI',
    // 名字
    title: 'KPI'
  },
  // XX
  xx: {
    // icon
    icon: 'icon-xx',
    // 名字
    title: 'xx'
  }
}

2.组件思路, 导入设定到的组件库与传入的图标名匹配.之后渲染出来.

全部代码

组件
<template lang="pug">
  header(class="multiple-header")
    span(class="header-icon")
      i(:class="aTopConfig.ClassList")
    span(class="header-title") {{ aTopConfig.title }}
</template>

<script>
import { iconType } from './static'
export default {
  name: 'TopIcon',
  props: {
    // 自定义icon
    icon: {
      type: String,
      default: () => {
        return ''
      }
    },
    // 自定义标题
    title: {
      type: String,
      default: () => {
        return ''
      }
    },
    // 提前配置好的类型
    type: {
      type: String,
      default: () => {
        return 'organization'
      }
    }
  },
  data () {
    return {
      // icon样式 class列表
      defaultIconClass: ['iconfont', 'icon-style']
    }
  },
  computed: {
    /**
     * 计算当前应该配置什么class
     * @return {Object} aTopConfig 返回当前头部标签
    */
    aTopConfig: function () {
      // 获取默认iconlist
      const { defaultIconClass, type } = this
      // 设置当前组件要的数据
      let aTopConfig = {
        // iconClass列表
        ClassList: [iconType[type].icon, ...defaultIconClass],
        // 标题
        title: iconType[type].title
      }
      return aTopConfig
    }
  }
}
</script>

<style lang="scss" scope>
  .icon-style {
    color: #9C9FAD
  }
  .multiple-header {
    height: 40px;
    line-height: 40px;
  }
  .header-title {
    font-size: 12px;
    color: #999999;
    margin-left: 3px;
  }
</style>

组件的使用
// html type为需要显示的icon名称如:kpi
TopIcon(:type="type")