1.在src/ 下面新建目录icons,里面新建文件夹svg,和文件index.js 。svg用于存放从iconfont下载下来的svg格式的图标,index.js用于引入使用到svg文件和对应的组件。

import Vue from 'vue'
import SvgIcon from '@/components/SvgIcon'// 自定义的svg组件
// register globally
Vue.component('svg-icon', SvgIcon)//在vue中全局引入图标组件

//引入所有的svg组件 const requireAll
= requireContext => requireContext.keys().map(requireContext) const req = require.context('./svg', false, /\.svg$/) const iconMap = requireAll(req)

  注意:“ require.context('./svg', false, /\.svg$/) ”表示引入 svg目录下的所有svg文件。 引入svg文件时,引入的文件路径要和实际路径保持一致

2.vue编译svg文件默认使用的是 url-loader ,我们需要安装 svg-sprite-loader 进行处理;

npm install svg-sprite-loader --save-dev

 再在 " \build\webpack.base.conf.js " 里面修改编译loader

 {
        test: /\.svg$/,
        loader: 'svg-sprite-loader',
        include: [resolve('src/icons')],//只有src/icons下的svg使用svg-sprite-loader编译
        options: { //编译时把svg的文件名前添加上icon,方便使用
          symbolId: 'icon-[name]'
        }
      },
      {
        test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
        loader: 'url-loader',
        exclude: [resolve('src/icons')],//src/icons下的svg文件都不使用url-loader编译
        options: {
          limit: 10000,
          name: utils.assetsPath('img/[name].[hash:7].[ext]')
        }
      },

3.新建字体图标组件,方便引用。“ src\components\SvgIcon\index.vue ” 新建组件,

<template>
  <svg :class="svgClass" aria-hidden="true">
    <use :xlink:href="iconName"></use>
  </svg>
</template>

<script>
export default {
  name: 'svg-icon',
  props: {
    iconClass: {
      type: String,
      required: true
    },
    className: {
      type: String
    }
  },
  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>

  组件格式是按照svg官网引用方式定义的组件,注意 “ :xlink:href="iconName" ”中的名称要和引入的svg文件名称一致。我们前面在webpack.base.conf.js中引用文件时添加了“ #icon- ” ,所以组件中的iconName也要添加“ #icon- ”,“ #icon- ”后面的名称要和引入的图标文件名一致。

4.使用svg图标。在页面中引用图标,只需要调用刚刚定义的组件就行。该组件我们前面在index,js中已经全局引入过了

 <svg-icon icon-class="404" class-name="svg-404"></svg-icon>

 上面的404图标就需要在 “ src/icons/svg/404.svg ” 下有对应的文件, “svg-404”是自定义的组件的样式。

学习链接: https://juejin.im/post/59bb864b5188257e7a427c09

posted on 2019-09-26 15:29  明明的喵喵  阅读(1307)  评论(0编辑  收藏  举报