1、下载插件svg-sprite-loader:
npm i svg-sprite-loader --save
2、写一个Svglcon的组件 (components/Svglcon),在components目录下新建一个SvgIcon文件夹,然后再新建一个index.vue文件,如: 3、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: 1.2em;
height: 1.2em;
vertical-align: -0.18em;
fill: currentColor;
overflow: hidden;
}
</style>
在html中就可以使用标签来使用,如:
<svg-icon icon-class="eye" class="color-main"></svg-icon>
其中icon-class指定的就是svg文件名,此时船体到组件中就是将eye传递给了iconClass,而当调用了
时,href=“iconName"就会调用iconName方法,最终href=”#icon-eye"l了。 4、在components在同一目录下新建一个icons目录,并在其中新建一个index.js文件,如: 其内容如下:
import Vue from 'vue'
import SvgIcon from '@/components/SvgIcon/index'
Vue.component('svg-icon', SvgIcon)
const requireAll = requireContext => requireContext.keys().map(requireContext)
const req = require.context('./svg', false, /\.svg$/)
requireAll(req)
注意:如果按照以上代码,那么icons文件夹下必须新建一个svg文件夹,并将svg文件放置到该文件夹下,如果svg在其他文件夹下,那么需要更改代码中的./svg换成指定的文件夹即可。 5、注册为全局组件了,但是并没有在其他地方来调用此方法,从而也不会生效,因此需要在main.js中引入一下icons的文件,如: 6、然后我们在html中使用 7、其实此时还不能正确的显示出来,还需要经过如下配置,在build/webpack.base.conf.js文件夹下进行配置,添加如下信息:
{
test: /\.svg$/,
loader: 'svg-sprite-loader',
include: [resolve('src/icons')],
options: {
symbolId: 'icon-[name]'
}
},
如下图所示: 配置完成后,如果直接编译会出现很多警告,如:
warning in ./src/icons/svg/password.svg
Module build failed: InvalidSvg: svg-sprite-loader exception.
module.exports = "data:image/svg+xml;base64,PD94b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g5MjMgMzguNDM5Mzg1IDY3LjgyMDMwOGwwIDg5LjYzOTM4NWMwIDIxLjc0MDMwOCAxNy4yNTA0NjIgMzkuNjk5NjkyIDM4LjQgMzkuNjk5NjkyczM4LjQtMTcuOTU5Mzg1IDM4LjQtMzkuNjk5NjkybDAtODkuNjM5Mzg1QzU3My40NCA3MjMuODg5MjMxIDU4OC44IDY5OC44OCA1ODguOCA2NjkuNDIwMzA4ek04OTYgNTEybDAgMzkzLjYwOTg0NmMwIDY1LjI2MDMwOC01MS44Njk1MzggMTE4LjM5MDE1NC0xMTUuMiAxMTguMzkwMTU0TDI0My4yIDEwMjRjLTYzLjI5MTA3NyAwLTExNS4yLTUzLjEyOTg0Ni0xMTUuMi0xMTguMzkwMTU0TDEyOCA1MTJjMC02NS4yMjA5MjMgNTEuODY5NTM4LTExOC4zOTAxNTQgMTE1LjItMTE4LjM5MDE1NGw1MzcuNiAwQzg0NC4xMzA0NjIgMzkzLjYwOTg0NiA4OTYgNDQ2Ljc3OTA3NyA4OTYgNTEyeiIgcC1pZD0iOTIzMCI+PC9wYXRoPjwvc3ZnPg=="
at Object.loader (D:\work\best\bt-mall-admin\node_modules\svg-sprite-loader\lib\loader.js:28:11)
@ ./src/icons/svg nonrecursive \.svg$
@ ./src/icons/index.js
@ ./src/main.js
@ multi (webpack)-dev-server/client?http://localhost:8081 webpack/hot/dev-server ./src/main.js
warning in ./src/icons/svg/eye.svg
8、这是由于url-loader也对svg进行了扫描,如下图所示: 因此我们需要在此处将src/icons目录从此处排除掉,也就是不让url-loader对该目录进行扫描,如: 9、此时在重新编译运行即可正常显示了,如:
|