1,vue中封装svg-icon组件
-
使用原因
- 1,svg是矢量图, 不会因为尺寸方法和缩小而失真
- 2, 阿里图库可以直接粘贴获取 svg 图标代码,方便快捷
- 3,封装为组件后,更容易操作
-
接下来我们一起来创造它吧
- 1,创建组件,首先在components文件夹下创建一个名为SvgIcon的文件夹,在此文件夹下创建 index.vue文件,如图:
comoponets/SvgIcon/index.vue
代码如下
- 1,创建组件,首先在components文件夹下创建一个名为SvgIcon的文件夹,在此文件夹下创建 index.vue文件,如图:
<template>
<svg :class="svgClass" aria-hidden="true" v-on="$listeners">
<use :xlink:href="iconName" />
</svg>
</template>
<script>
export default {
name: 'SvgIcon',
props: {
iconClass: {
type: String,
required: true
},
className: {
type: String,
default: ''
}
},
computed: {
iconName() {
return `#icon-${this.iconClass}`
},
svgClass() {
if (this.className) {
return 'svg-icon ' + this.className
} else {
return 'svg-icon'
}
}
}
}
</script>
<style scoped>
.svg-icon {
width: 1em;
height: 1em;
vertical-align: -0.15em;
fill: currentColor;
overflow: hidden;
}
</style>
- 2,将上一步中的svg 所需文件 放入icons/svg/目录下,并在icons文件夹下创建 index.js,代码如下
- 3 ,引入vue, 注册 svg-icon全局组件, 下一步要配置 svg-sprite-loader
// icons/index.jsindex.jsicons
import Vue from 'vue'
import SvgIcon from '@/components/SvgIcon'// svg组件
// register globally
Vue.component('svg-icon', SvgIcon)
const req = require.context('./svg', false, /\.svg$/)
const requireAll = requireContext => requireContext.keys().map(requireContext)
requireAll(req)
到目前为止使用 < svg-icon icon-class=“left-indent” /> 还没有效果,因为还缺少配置文件
2,vue/cli4 vue.config.js
中配置 svg-sprite-loader
- 为 svg配置 svg-sprite-loader
npm install svg-sprite-loader -D
- 我用的是vue/cli 4 ,查询官方文档可看见如图配置
vue/cli官方地址链接
- 使用chainWebpack方法可自定义配置 loader
vue.config.js
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()
}
}
- 重启项目 报错:
error: resolve is not defined
3, vue.config.js
报错:resolve is not defined !
- 在
vue.config.js
中没有配置 resolve 方法, 需要自定义一个,代码如下:
const path = require('path')
function resolve(dir) {
return path.join(__dirname, dir)
}
- 然后重启项目就大功告成了!
- 使用代码如下