一,components路径下创建一个IconSvg.vue组件,内容如下:
<template>
<svg class="svg-icon" aria-hidden="true">
<use :xlink:href="iconName"></use>
</svg>
</template>
<script>
export default {
name: 'icon-svg',
props: {
iconClass: {
type: String,
required: true
}
},
computed: {
iconName() {
return `#icon-${this.iconClass}`
}
}
}
</script>
<style>
.svg-icon {
width: 6em;
height: 6em;
vertical-align: -0.15em;
fill: blue;
overflow: hidden;
}
</style>
二,在assets路径下创建icons文件夹,里面创建svg文件夹和index.js,把svg文件导入svg文件夹下
index.js里面的内容:
import Vue from 'vue'
import IconSvg from '@/components/IconSvg'
Vue.component('icon-svg',IconSvg)
const requireAll = requireContent => {requireContent.keys().map(requireContent)}
const req = require.context('./svg',false,/\.svg$/)
requireAll(req)
三,在入口文件main.js中导入index.js
import '../src/assets/icons/index'
四,安装svg-sprite-loader
npm install svg-sprite-loader -D
配置:webpack.base.conf.js,内容如下;
{
test: /\.svg$/,
loader: 'svg-sprite-loader',
include: [resolve('src/assets/icons')],
options: {
symbolId: 'icon-[name]'
}
},
{
test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
loader: 'url-loader',
exclude: [resolve('src/assets/icons')],
options: {
limit: 10000,
name: utils.assetsPath('img/[name].[hash:7].[ext]')
}
},
五,在组件中使用,
<icon-svg icon-class="book"></icon-svg>
更多的配置可以参考:https://juejin.im/post/59bb864b5188257e7a427c09#heading-10