1、创建SvgIcon组件,在vue项目的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>
2、创建icons文件夹,src根目录下创建icons文件夹,里面创建svg文件夹和index.js文件,index.js代码如下:
import Vue from 'vue'
import SvgIcon from '@/components/SvgIcon'// svg component
// register globally
Vue.component('svg-icon', SvgIcon)
const req = require.context('./svg', false, /\.svg$/)
const requireAll = requireContext => requireContext.keys().map(requireContext)
requireAll(req)
3、main.js中引入
import './icons'
4、下载插件
npm i svg-sprite-loader --save
5、在build/webpack.base.conf.js文件中,加入以下代码:
{
test: /\.svg$/,
loader: 'svg-sprite-loader',
include: [resolve('src/icons')],
options: {
symbolId: 'icon-[name]'
}
}
6、在build/webpack.base.conf.js文件中原代码中加入exclude: [resolve('src/icons')],代码。原代码如下:
{
test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
loader: 'url-loader',
exclude: [resolve('src/icons')],
options: {
limit: 10000,
name: utils.assetsPath('img/[name].[hash:7].[ext]')
}
},
7、在vue页面使用。user对应src/icons/svg目录下的图标文件名称
<svg-icon icon-class="user" />