下载安装 svg
npm install svg-sprite-loader --save-dev
配置config文件 在vue.config.js
'use strict'
const path = require('path')
function resolve(dir) {
return path.join(__dirname, dir)
}
module.exports = {
chainWebpack (config) {
// when there are many pages, it will cause too many meaningless requests
config.plugins.delete('prefetch')
// 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()
}
}
创建icon文件夹,存放svg格式图片
icon/index.js
import Vue from 'vue'
import SvgIcon from '@/components/SvgIcon'// svg component
// register globally
Vue.component('svg-icon', SvgIcon)
const req = require.context('./svg', false, /\.svg$/)
const req2 = require.context('./svg2', false, /\.svg$/)
const req3 = require.context('./svgxun', false, /\.svg$/)
const requireAll = requireContext => requireContext.keys().map(requireContext)
requireAll(req)
requireAll(req2)
requireAll(req3)
创建组件components ---> SvgIcon
<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>
src/utils/validate.js
//加入
export function isExternal(path) {
return /^(https?:|mailto:|tel:)/.test(path)
}
在main.js引入
开始正式使用
<div>
<svg-icon icon-class="shopping" class-name="card-panel-icon" />
</div>
我遇到一个问题 报错提示:
Missing required prop: "iconClass" found in --->
<SvgIcon> at src/components/SvgIcon/index.vue
.....
说是缺少必要属性 查看前人代码最后.....
<el-input class="login-input" v-model="loginForm.code" @keyup.enter.native="handleLogin">
<!--就是因为 没有icon-class属性所以会报上边的错 -->
<svg-icon slot="prefix" class="el-input__icon input-icon validCode" />
</el-input>
//结果看style
<style rel="stylesheet/scss" lang="scss">
.validCode {
background: url("../assets/image/verification.png") no-repeat;
background-size: 18px 21px;
}
</style>