在VUE中使用svg
在VUE中使用svg
svg与传统图片相比的优劣势
优势:
- 矢量图,可无限放大缩小、随意切换颜色、修改内容,不失真
- 基于xml,浏览器可读,有利SEO
- 图标多时渲染效率高
劣势:
- 设计师设计相对麻烦
vue中封装步骤
一、安装依赖
npm install svg-sprite-loader --save-dev
二、编写svg组件
我是存放在src/components/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>
import { isExternal } from '@/utils/validate'
export default {
name: 'SvgIcon',
props: {
iconPath: {
type: String,
required: true
},
className: {
type: String,
default: ''
}
},
computed: {
isExternal() {
return isExternal(this.iconPath)
},
iconName() {
return `#icon-${this.iconPath}`
},
svgClass() {
if (this.className) {
return 'svg-icon ' + this.className
} else {
return 'svg-icon'
}
},
styleExternalIcon() {
return {
mask: `url(${this.iconPath}) no-repeat 50% 50%`,
'-webkit-mask': `url(${this.iconPath}) 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>
validate.js文件:
/**
* @param {string} path
* @returns {Boolean}
*/
export function isExternal(path) {
return /^(https?:|mailto:|tel:)/.test(path)
}
三、全局注册svg组件
src/assets/icons/index.js
import Vue from 'vue'
import SvgIcon from '@/components/SvgIcon'// svg component
// 全局注册
Vue.component('svg-icon', SvgIcon)
// 引入所有svg文件
const req = require.context('./svg', false, /\.svg$/)
const requireAll = requireContext => requireContext.keys().map(requireContext)
requireAll(req)
四、全局引入写着第三步代码的文件
main.js
import './assets/icons'
五、配置loader
根目录下的vue.config.js文件中
const path = require("path");
const resolve = str => path.join(__dirname, str);
module.exports = {
chainWebpack: (config) => { // 接收一个基于 webpack-chain 的 ChainableConfig 实例
// 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()
}
}
使用方式
<svg-icon class-name="" icon-path="double-arrow" />