安装 svg-sprite-loader
npm install svg-sprite-loader --save
封装组件
目录结构
.
│ App.vue
│ main.js
├─components
│ └─SvgIcon
│ index.vue
│
├─router
│ index.js
│
├─store
│ actions.js
│ index.js
│ mutations.js
│
├─svgIcons
│ │ index.js
│ │
│ └─svg
│ certification.svg
│
给看官老爷奉上code
cd 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>
.svg-icon{
width: 1em;
height: 1em;
vertical-align: -0.15em;
fill: currentColor;
overflow: hidden;
}
</style>
cd src/svgIcons/index.js
import Vue from "vue"
import SvgIcon from "@/components/SvgIcon"
Vue.component("svg-icon",SvgIcon);
const req = require.context("./svg",false,/\.svg$/)
const requireAll = requireContext => requireContext.keys().map(requireContext)
requireAll(req)
src/svgIcons/svg/xxx.svg
cd src/main/js
import './svgIcons'
修改webpack配置
-
增加loader
{ test: /\.svg$/, loader: 'svg-sprite-loader', include: [resolve('src/svgIcons')], options: { symbolId: 'icon-[name]' } }
.. admonition:: 提示
- 如果url-loader 已经引入了 svg 需要先排除(exclude),如下代码。
{
test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
loader: 'url-loader',
exclude: [resolve('src/svgIcons')],
options: {
limit: 10000,
name: utils.assetsPath('img/[name].[hash:7].[ext]')
}
}
到此准备工作全部就绪,如何在业务代码里使用?必杀技 :
<svg-icon icon-class='xxx' class="" style=""></svg-icon>
<p style="color: #FFB6C1">一招毙命 , 打完收工,✿✿ヽ(°▽°)ノ✿</p>