赞
踩
安装/下载依赖
npm install svg-sprite-loader -D
svg-sprite-loader 配置:在vue.config.js中配置
// vue.config.js文件
// 导入模块
const path = require('path')
// 获取路径
function resolve (dir) {
return path.join(__dirname, dir)
}
// 配置
module.exports = {
//...
chainWebpack(config) {
config.plugins.delete('preload') // TODO: need test
config.plugins.delete('prefetch') // TODO: need test
// set svg-sprite-loader
config.module
.rule('svg')
.exclude.add(resolve('src/assets/icons'))
.end()
config.module
.rule('icons')
.test(/\.svg$/)
.include.add(resolve('src/assets/icons'))
.end()
.use('svg-sprite-loader')
.loader('svg-sprite-loader')
.options({
symbolId: 'icon-[name]'
})
.end()
}
}
创建svgIcon插件
步骤
-
// icons/index.js
import Vue from 'vue'
import SvgIcon from '@/components/SvgIcon'// 封装的svgIon组件
// register globally
Vue.component('svg-icon', SvgIcon)
// 统一批量引入
const req = require.context('./svg', false, /\.svg$/) // ./svg -> svg文件所在路径
const requireAll = requireContext => requireContext.keys().map(requireContext)
requireAll(req)
在icons下创建 svg文件夹 管理所有的svg文件

封装 svg-icon 全局组件
components 下创建 SvgIcon 组件(component专门放共用组件的)
<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>
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>
External 方法
export function isExternal (path) {
return /^(https?:|mailto:|tel:)/.test(path)
}
import './assets/icons' // icon
// 或者
import svgIconPlugin from '@/icons/index.js'
Vue.use(svgIconPlugin)
使用
<template>
<div>
<svg-icon icon-class="404" class="fs20" />
</div>
</template>
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。