vue中svg的使用

1、安装svg-sprite-loader

npm install svg-sprite-loader

2、在webpack.base.conf.js中配置svg-sprite-loader

{
    test: /\.svg$/,
    loader: 'svg-sprite-loader',
    include: [resolve('src/icon')], // 存放路径
    options: {
        symbolId: 'icon-[name]' // name代表图标名字
    }
}

3、图片默认是放在img/下面的,因此需要在webpack.base.conf.js中加入exclude: [resolve('src/icons')],这里的路径和步骤2中路径要保持一致

{
  test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
  loader: 'url-loader',
  exclude: [resolve('src/icons')], // 配置svg时新添加的
  options: {
    limit: 10000,
    name: utils.assetsPath('img/[name].[hash:7].[ext]')
  }
}

4、由于显示等其他原因,我这边在src/components/SvgIcon/index.vue进行了简单的封装处理,以下是全部代码(:

<template>
  <svg :class="svgClass" aria-hidden="true" v-on="$listeners">
    <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'
      }
    },
    styleExternalIcon () {
      return {
        mask: `url(${this.iconClass}) no-repeat 50% 50%`,
        '-webkit-mask': `url(${this.iconClass}) no-repeat 50% 50%`
      }
    }
  }
}
</script>

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

.svg-external-icon {
  background-color: currentColor;
  mask-size: cover!important;
  display: inline-block;
}
</style>

5、创建 src/icons/index.js,自动引入src/icons下的所有图标,文件内容如下:

import Vue from 'vue'
import SvgIcon from '@/components/SvgIcon' // 对svg组件进行简单封装处理

// register globally
Vue.component('svg-icon', SvgIcon)

const req = require.context('./svg', false, /\.svg$/)
const requireAll = requireContext => requireContext.keys().map(requireContext)
requireAll(req)

6、最外层的main.js中引入

import '@/icons'

7、需要使用的vue页面添加下面的代码,svg文件放在src/icons/svg文件夹下

<svg-icon icon-class="svg文件名(不带.svg后缀)" />

注:参考GitHub上面的vue-element-admin-master项目

猜你喜欢

转载自blog.csdn.net/huangge1199/article/details/107559580