Use svg in vue2
Take the vue2 project as an example
1. Download loader
npm i svg-sprite-loader
2. Create svg related components
Create a folder src
under the file, and the content of the components under the file is as follows:components
SvgIcon
index.vue
<template>
<svg :class="['svg-icon', className]" 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}`;
},
},
};
</script>
<style scoped>
// svg图标样式,可自行进行修改
.svg-icon {
width: 10rem;
height: 10rem;
vertical-align: -0.15em;
fill: currentColor;
overflow: hidden;
}
</style>
3. Create svg global components
src
Created under utils
, the file created utils
under , the content is as followsicons
index.js
import Vue from "vue";
// svg组件
import SvgIcon from "@/components/SvgIcon";
// 全局组件注册
Vue.component("SvgIcon", SvgIcon);
// 工程化导入所有 svg 资源(context后面即svg资源放置路径)
const req = require.context("../../assets/icons/svg", false, /\.svg$/);
const requireAll = (requireContext) =>
requireContext.keys().map(requireContext);
requireAll(req);
4. SVG configuration in vue.config.js
const path = require("path");
/**
* 路径替换
* @Date: 2022-09-27 10:48:54
* @param {string} dir: 需要替换的文件路径
* @return {string} 替换后的文件绝对地址
*/
function resolve(dir) {
return path.join(__dirname, dir);
}
module.exports = {
chainWebpack: (config) => {
/**
* 将svg图片以雪碧图的方式在项目中加载
*/
config.module
.rule('svg')
.exclude.add(resolve('src/assets/icons'))
.end()
config.module
.rule('icons')
.test(/\.svg$/)
.include.add(resolve('src/assets/icons')) // svg所在路径
.end()
.use('svg-sprite-loader')
.loader('svg-sprite-loader')
.options({
// 参数配置
symbolId: 'icon-[name]',
})
},
};
5. Introduced in main.js
import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
// 引入svg相关文件
import './utils/icons/index.js'
Vue.config.productionTip = false
new Vue({
router,
store,
render: function (h) {
return h(App) }
}).$mount('#app')
6. Use in vue page
<template>
<div class="home">
// iconClass即svg的文件名
<SvgIcon iconClass="heart" />
</div>
</template>
<script>
export default {
name: 'Home',
}
</script>
What I introduced is a heart-shaped svg
picture downloaded from the Alibaba vector icon library, and the effect is as follows: