在VUE项目中使用svg图标
安装项目依赖
npm i svg-sprite-loader@4.1.3
这里之后打包的时候,可能会报非常多错误,比如:Error Cannot find module ‘webpacklibRuleSet‘
若有报这个错误,重新安装一下webpack
npm i webpack@4.29.5 --force
在src目录下新建文件夹
index.vue:
<template>
<div v-if="isExternal" :style="styleExternalIcon" class="svg-external-icon svg-icon" v-on="$listeners" />
<svg v-else :class="svgClass" aria-hidden="true" v-on="$listeners">
<use :xlink:href="iconName" />
</svg>
</template>
<script>
// doc: https://panjiachen.github.io/vue-element-admin-site/feature/component/svg-icon.html#usage
import { isExternal } from '../../utils/validate'
export default {
name: 'SvgIcon',
props: {
iconClass: {
type: String,
required: true
},
className: {
type: String,
default: ''
}
},
computed: {
isExternal() {
return isExternal(this.iconClass)
},
iconName() {
return `#icon-${this.iconClass}`
},
svgClass() {
if (this.className) {
return 'svg-icon ' + this.className
} else {
return 'svg-icon'
}
},
styleExternalIcon() {
return {
mask: `url(${this.iconClass}) no-repeat 50% 50%`,
'-webkit-mask': `url(${this.iconClass}) no-repeat 50% 50%`
}
}
}
}
</script>
<style scoped>
.svg-icon {
width: 1.2em;
height: 1.2em;
/* vertical-align: -0.15em; */
fill: currentColor;
overflow: hidden;
}
.svg-external-icon {
background-color: currentColor;
mask-size: cover !important;
display: inline-block;
}
</style>
在src目录下新建文件夹
index.js:
import Vue from 'vue'
import SvgIcon from '@/components/SvgIcon'// svg component
// register globally
Vue.component('SvgIcon', SvgIcon)
const req = require.context('./svg', false, /\.svg$/)
const requireAll = requireContext => requireContext.keys().map(requireContext)
requireAll(req)
在svg中放我们需要引用的svg图片
在main中引用:
Vue.config.productionTip = false
import '@/icons'
配置 vue.config.js
const { defineConfig } = require('@vue/cli-service')
const path = require("path");
function resolve(dir) {
return path.join(__dirname, dir);
}
module.exports = defineConfig({
transpileDependencies: true,
chainWebpack (config) {
// set svg-sprite-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]'
})
.end()
}
})
使用
<SvgIcon
icon-class="limit"
class="item_icon"
></SvgIcon>
去掉可以改svg颜色
参考:
https://blog.csdn.net/m0_57524265/article/details/131487957?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522170243566916800197061381%2522%252C%2522scm%2522%253A%252220140713.130102334…%2522%257D&request_id=170243566916800197061381&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2allsobaiduend~default-1-131487957-null-null.142v96pc_search_result_base7&utm_term=svg%20vue&spm=1018.2226.3001.4187