如何在vue脚手架中使用svg图标
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) {
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
创建如下格式的文件结构
import Vue from 'vue'
import SvgIcon from '@/components/SvgIcon'
Vue.component('svg-icon', SvgIcon)
const req = require.context('./svg', false, /\.svg$/)
const requireAll = requireContext => requireContext.keys().map(requireContext)
requireAll(req)
2) 组件 位置 componets/SvgIcon/index.vue
// 位置 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
export function isExternal(path) {
return /^(https?:|mailto:|tel:)/.test(path)
}
export function validMobile(str) {
return /^1[3-9]\d{9}$/.test(str)
}
-
在main.js中引入 import '@/icons'
5.使用
使用格式<svg-icon icon-class="文件名"/> 。这里的文件名就是在src/icons/svg下的文件名
<svg-icon icon-class="404"/>
|