1. 安装依赖
npm install svg-sprite-loader --save-dev |
2. 在 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' | |
} | |
} | |
} | |
} | |
</script> | |
<style scoped> | |
.svg-icon { | |
width: 1em; | |
height: 1em; | |
vertical-align: -0.15em; | |
fill: currentColor; | |
overflow: hidden; | |
} | |
</style> |
3. 在 src/icons 下新建 index.js 文件, index.js 文件内容如下
import Vue from 'vue' | |
import SvgIcon from '../../components/SvgIcon'// 引入 svg 组件 | |
// 全局注册 | |
Vue.component('svg-icon', SvgIcon) | |
const req = require.context('./svg', false, /\.svg$/) | |
const requireAll = requireContext => requireContext.keys().map(requireContext) | |
requireAll(req) |
4. 在 main.js 中引入 /icons/index.js 文件
import i18n from './lang' | |
import './icons' | |
import './permission' |
5. 在 vue.config.js 文件中配置
const path = require('path'); | |
function resolve(dir) { | |
return path.join(__dirname, dir) | |
} | |
chainWebpack(config) { | |
config.plugins.delete('preload') | |
config.plugins.delete('prefetch') | |
// set svg-sprite-loader | |
config.module | |
.rule('svg') | |
.exclude.add(resolve('src/assets/icons')) | |
.end() | |
config.module | |
.rule('icons') | |
.test(/\.svg$/) | |
.include.add(resolve('src/assets/icons')) | |
.end() | |
.use('svg-sprite-loader') | |
.loader('svg-sprite-loader') | |
.options({ | |
symbolId: 'icon-[name]' | |
}) | |
.end() | |
} |
6. 项目中使用
在 src/icons/svg 下新建 user.svg
<svg width="130" height="130" xmlns="http://www.w3.org/2000/svg"><path d="M63.444 64.996c20.633 0 37.359-14.308 37.359-31.953 0-17.649-16.726-31.952-37.359-31.952-20.631 0-37.36 14.303-37.358 31.952 0 17.645 16.727 31.953 37.359 31.953zM80.57 75.65H49.434c-26.652 0-48.26 18.477-48.26 41.27v2.664c0 9.316 21.608 9.325 48.26 9.325H80.57c26.649 0 48.256-.344 48.256-9.325v-2.663c0-22.794-21.605-41.271-48.256-41.271z" stroke="#979797"/></svg> |