记录自己Vue2使用SVG的过程
package.json 的版本
"svgo": "1.3.2",
"svg-sprite-loader": "4.2.1",
需要执行的命令
npm install svgo
npm install svg-sprite-loader
创建一个icons文件夹并创建以下文件
打开 icons/index.js 并写入
ps: ./svg 为svg文件夹,里面存放SVG图片
const req = require.context('./svg', false, /\.svg$/)
const requireAll = requireContext => requireContext.keys().map(requireContext)
requireAll(req)
打开 icons/svgo.yml 并写入
# replace default config
# multipass: true
# full: true
plugins:
# - name
#
# or:
# - name: false
# - name: true
#
# or:
# - name:
# param1: 1
# param2: 2
- removeAttrs:
attrs:
- 'fill'
- 'fill-rule'
ps: 该 svgo.yml 文件主要作用于 package.json, 可添加一条命令并执行, 可查看定义的文件夹下的SVG图片信息
"scripts": {
"svgo": "svgo -f src/你所定义的路径/icons/svg --config=src/pages/test/x6/icons/svgo.yml",
}
前往 vue.config.js 配置SVG
ps: 我的 icons 文件夹 定义在 src 文件夹下
chainWebpack: config => {
//配置SVG
config.module
.rule('svg')
.exclude.add(resolve('src/你所定义的路径/icons'))
.end()
config.module
.rule('icons')
.test(/\.svg$/)
.include.add(resolve('src/你所定义的路径/icons'))
.end()
.use('svg-sprite-loader')
.loader('svg-sprite-loader')
.options({
symbolId: 'icon-[name]'
})
.end()
},
封装SVG组件, 需要引入 icons 文件夹下的 index.js
SvgIcon.vue
<template>
<svg :class="svgClass" aria-hidden v-on="$listeners">
<title>{{ title }}</title>
<use :xlink:href="iconName" />
</svg>
</template>
<script>
//引入 icons 文件夹下的 index.js
import "../icons/index"
export default {
name: "SvgIcon",
props: {
title: {
type: String,
default: "",
},
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 scoped>
.svg-icon {
width: 10em;
height: 10em;
vertical-align: -0.15em;
fill: currentColor;
overflow: hidden;
}
</style>
在封装完成后, 前往 main.js 注册为全局组件
//引入 icons 文件夹
import "/src/你所定义的路径/icons"
//封装的 SvgIcon.vue
const SvgIcon = () => import("./你所定义的路径/SvgIcon")
const components = {
SvgIcon
}
Object.keys(components).forEach(item => {
Vue.component(item,components[item])
})
完成上述所有后, 根据自己的需求在所需组件中引入SvgIcon.vue并配置, 启动项目, 即可