首先还是安装依赖包:
npm install svg-sprite-loader svgo-loader --D
vue.config.js中的webpack配置
const { resolve } = require('path') module.exports = { chainWebpack: config => { config.module .rule('svg') .exclude.add(resolve('src/assets/icons/')) .end() config.module .rule('svg-sprite') .test(/\.svg$/) // 处理svg目录 .include.add(resolve('src/assets/icons/')) .end() .use('svg-sprite-loader') .loader('svg-sprite-loader') .options({ symbolId: 'icon-[name]' }) .end() .before('svg-sprite-loader') .use('svgo-loader') .loader('svgo-loader') .options({ plugins: [ { name: 'removeAttrs', params: { attrs: '(fill|stroke)' } }, { name: 'removeTitle' } ] }) .end() } }
创建vue组件SvgIcon.vue
<template> <svg class="svg-icon" :class="{ 'icon-spin': spin }" aria-hidden="true" v-on="$listeners"> <use :xlink:href="`#icon-${iconName}`"/> </svg> </template> <script> export default { name: 'SvgIcon', props: { iconName: { type: String, required: true }, spin: { type: Boolean, default: false } } } </script> <style scoped> .svg-icon { stroke: currentColor; fill: currentColor; cursor: pointer; margin-bottom: 0.125em; vertical-align: middle; height: 1em; width: 1em; } .svg-icon .icon-spin { animation: icon-spin 2s infinite linear; } @keyframes icon-spin { from { transform: rotate(0deg); } to { transform: rotate(359deg); } } </style>
注册组件,我的是在main.js中全局注册组件
import Vue from 'vue' // svg图标 import SvgIcon from './components/svgIcon/SvgIcon' Vue.component('svg-icon', SvgIcon) // 把路径/assets/icons/下面的svg文件全局注册 const svgIcons = require.context('@/assets/icons/', false, /\.svg$/) const requireAll = requireContext => requireContext.keys().map(requireContext) requireAll(svgIcons)
测试组件:在文件夹src/assets/icons/下面放一张icon-2X2.svg
下面是一个Test.vue测试组件
<template> <svg-icon class="icons-button" icon-name="icon-2X2" /> </template> <script> export default { name: 'Test' } </script> <style scoped> .icons-button { color: darkgreen; //cursor: pointer; &:hover { color: coral; } } </style>