通用组件—SvgIcon引入和使用
IconSvg-Icon创建一个专门放置图标 icon 的文件夹:src/icons添加SvgIcon组件到公共components目录下src/components/SvgIcon/index.vue<template><div v-if="isExternal" :style="styleExternalIcon" class="svg-external-icon svg-i
·
Svg-Icon
-
创建一个专门放置图标 icon 的文件夹:
src/icons
-
添加SvgIcon组件到公共components目录下
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>
export default {
name: 'SvgIcon',
props: {
iconClass: {
type: String,
required: true
},
className: {
type: String,
default: ''
}
},
computed: {
isExternal() {
return /^(https?:|mailto:|tel:)/.test(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>
-
添加 index.js 全局注册svg-icon组件
src/icons/index.js
import Vue from 'vue'
import SvgIcon from '@/components/SvgIcon'// svg component
// 全局注册组件
Vue.component('svg-icon', SvgIcon)
// 全局自动导入所有svg图标
// 这行代码就会去 svg 文件夹(不包含子目录)下面的找所有文件名以 .svg 结尾并能被 require 的文件
const req = require.context('./svg', false, /\.svg$/)
const requireAll = requireContext => requireContext.keys().map(requireContext)
requireAll(req)
- 在main.js中引入
import '@/icons' // icon
- 安装svg-sprite-loader(注意版本不要过高),并在vue.config.js中配置
chainWebpack(config) {
...
// set svg-sprite-loader
config.module
.rule('svg')
.exclude.add(resolve('src/icons')) // 排除掉其他loader对svg处理
.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()
...
}
如果是直接配置webpack,则如下
{
test: /\.(png|jpe?g|gif|svg|cur)(\?.*)?$/,
loader: 'file-loader',
exclude: [resolve('src/icons')], //添加此行
options: {
esModule: false,
name: 'images/[name].[ext]?[hash]'
}
},
{
test: /\.svg$/,
loader: 'svg-sprite-loader',
include: [resolve('src/icons')],
options: {
symbolId: 'icon-[name]'
}
}
可选:安装 svgo,通过配置 svgo.yml
从启动项优化svg,或者安装 svgo-loader,在webpack中配置,优化svg
- 使用
<!-- icon-class 为 icon 的名字; class-name 为 icon 自定义 class-->
<svg-icon icon-class="password" class-name='custom-class' />
更多推荐
已为社区贡献1条内容
所有评论(0)