vue2导入svg
第一步:src->components目录下新建SvgIcon文件夹,文件夹下新建index.vue文件
示意图:
代码:
<template>
<svg :class="svgClass" aria-hidden="true">
<use :xlink:href="iconName"/>
</svg>
</template>
<script>
export default {
name: 'SvgIcon',
props: {
iconClass: {
type: String,
required: true
},
className: {
type: String
}
},
computed: {
iconName() {
return `#icon-${this.iconClass}`
},
svgClass() {
if (this.className) {
return this.className
} else {
return 'svg-icon'
}
}
}
}
</script>
<style scoped>
.svg-icon {
width: 2em;
height: 2em;
vertical-align: -0.6em;
fill: currentColor;
overflow: hidden;
}
.nav-svg-icon{
width: 4em;
height: 4em;
vertical-align: -0.15em;
fill: currentColor;
overflow: hidden;
}
</style>
第二步:src目录下新建icons文件夹,文件夹下新建svg文件夹和index.js文件,svg文件夹用于存放svg文件
import Vue from 'vue'
import SvgIcon from '@/components/SvgIcon'// svg component
// register globally
Vue.component('svg-icon', SvgIcon)
const req = require.context('./svg', false, /\.svg$/)
const requireAll = requireContext => requireContext.keys().map(requireContext)
requireAll(req)
第三步:安装插件:svg-sprite-loader
命令:
npm install svg-sprite-loader --save
第四步:vue.config.js配置
代码:
const { defineConfig } = require("@vue/cli-service");
const path = require("path");
// 引入path模块
function resolve(dir) {
return path.join(__dirname, dir);
}
module.exports = defineConfig({
...
chainWebpack: (config) => {
// 配置 vue-svg-loader
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]",
});
},
});