1.下载模块
npm install --save-dev svg-sprite-loader
2.在components下新建SvgIcon.vue文件:
<template>
<svg :class="getClassName" :width="width" :height="height" aria-hidden="true" v-on="$listeners">
<use :xlink:href="getName"></use>
</svg>
</template>
<script>
export default {
name: 'icon-svg',
props: {
name: {
type: String,
required: true
},
className: {
type: String
},
width: {
type: String
},
height: {
type: String
}
},
computed: {
getName() {
return `#icon-${this.name}`
},
getClassName() {
return ['icon-svg', `icon-svg__${this.name}`, this.className && /\S/.test(this.className) ? `${this.className}` : '']
}
}
}
</script>
<style>
.icon-svg {
width: 1rem;
height: 1rem;
fill: currentColor;
overflow: hidden;
}
</style>
3.src下新建icons文件夹,放svg文件和 index.js如下:
svg文件命名以icon-aaa形式
index.js文件如下:
import Vue from 'vue'
import IconSvg from '../components/SvgIcon.vue'
Vue.component('IconSvg', IconSvg)
const svgFiles = require.context('./svg', true, /\.svg$/)
const iconList = svgFiles.keys().map(item => svgFiles(item))
console.log(svgFiles,iconList);
export default {
getNameList () {
return iconList.map(item => item.default.id.split('-')[1])
}
}
4.使用
<icon-svg name="aaa" class="icon"></icon-svg>
<style>
.icon{
width:100px;
height:100px;
color:red;
}
</style>
5.如果不报错,图形没出来,可能需要编译插件
npm install babel-polyfill
6.在build下的webpack.base.conf.js文件中,entry改为:
entry: {
app: ['babel-polyfill', './src/main.js']
},
7.核查目录