一.如何在新项目使用svg-icon组件 步骤
1.安装依赖
npm i svg-sprite-loader@4.1.3
2.配置 vue.config.js
const path = require('path')
function resolve (dir) {
return path.join(__dirname, dir)
}
补充一个配置{ }
module.exports ={
// 省略其他...
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()
}
3.创建文件
(1) src/icons
src/icons
- /svg # 保存图标
- /index.js # 注册全局组件
- ```
(2) 组件
```js
componets/SvgIcon/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: 1em;
height: 1em;
vertical-align: -0.15em;
fill: currentColor;
overflow: hidden;
}
.svg-external-icon {
background-color: currentColor;
mask-size: cover!important;
display: inline-block;
}
</style>
(3)validate.js
utils/validate.js
(4)在main.js中引入
import '@/icons'
(5)使用 使用格式<svg-icon icon-class="文件名"/>
。这里的文件名就是在src/icons/svg
下的文件名
这个文件名必须是你项目里面有这个图片文件名才可以正常显示
没有这个文件也无法显示出来