红叶都枫了 @163

vue-在公共icon封装组件里使用svg图标

1.安装svg-sprite-loader。package.json:"svg-sprite-loader": "^3.9.2",

2.build/webpack.base.conf.js的model.rules新增配置:

{
        test: /\.svg$/,
        loader: 'svg-sprite-loader',
        include: [resolve('src/icons')],
        options: {
          symbolId: 'icon-[name]'
        }
      },
      {
        test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
        loader: 'url-loader',
        exclude: [resolve('src/icons')],
        options: {
          limit: 10000,
          name: utils.assetsPath('img/[name].[hash:7].[ext]')
        }
      },

3.components下新建SvgIcon/index.vue文件,内容:

<template>
<svg :class="svgClass" aria-hidden="true">
    <use :xlink:href="iconName"/>
</svg>
</template>
<script>
export default {
name: 'SvgIcon',
props: {
    iconClass: {
    type: String,
    required: true
    },
    className: {
    type: String,
    default: ''
    }
},
computed: {
    iconName() {
    return `#icon-${this.iconClass}`
    },
    svgClass() {
    if (this.className) {
        return 'svg-icon ' + this.className
    } else {
        return 'svg-icon'
    }
    }
  }
}
</script>

<style scoped>
.svg-icon {
    width: 1em;
    height: 1em;
    vertical-align: -0.15em;
    fill: currentColor;
    overflow: hidden;
}
</style>

4.src下新建icons/svg文件夹和icons/index.js文件,前者放置所有.svg文件,后者内容为:

import Vue from 'vue'
import SvgIcon from '@/components/SvgIcon'// 引入svg组件

// 注册全局组件
Vue.component('svg-icon', SvgIcon)
// require.context,通过正则匹配到可能的文件,全部引入
const req = require.context('./svg', false, /\.svg$/)
const requireAll = requireContext => requireContext.keys().map(requireContext)
requireAll(req)

5.在main.js中引入的公共js文件里引入icons下所有文件:

import '@/icons'

6.页面使用,icon-class就是之前存放在src/svg下的各个.svg文件名称:

<svg-icon icon-class="warning" />
<svg-icon icon-class="why" />

放个链接

posted @ 2020-12-09 11:17  红叶都枫了163  阅读(589)  评论(0编辑  收藏  举报