要点
- 在
src/icon/index
中注册成立单独的组件 - 在
main.js
中引入src/icon/index
中定义的组件 - 需要下载svg-sprite-loader@4.1.3的配合使用,以及在对应的
vue.config.js
里面的配置 - 它的使用格式是:
//这里的文件名就是src/icon/svg下的文件名<icon-svgclass="文件名"/>
使用步骤
第一步
## npm 包管理下载npminstall svg-spriye-loader@4.1.3## yarn 包管理器下载yarnadd svg-spriye-loader@4.1.3
第二步,配置vue.config.js
文件
const path=require('path')functionresolve(dir){return path.join(__dirname, dir)}
在module.exports 中补充一个配置:chainWebpack(config){// 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()}
第三步,赋值创建文件
1).src/icon
src/icon-- svg ## 保存图标--./index.js ##注册全局组件
/index.js
的内容
import Vuefrom'vue'import SvgIconfrom'@/components/SvgIcon'
Vue.component('svg-icon', SvgIcon)const req= require.context('./svg',false,/\.svg$/)constrequireAll=requireContext=> requireContext.keys().map(requireContext)requireAll(req)
2)在mian.js
中引入组件:
import src/componets/SvgIcon/index.vue
在组件中使用
<template><divv-if="isExternal":style="styleExternalIcon"class="svg-external-icon svg-icon"v-on="$listeners"/><svgv-else:class="svgClass"aria-hidden="true"v-on="$listeners"><use:xlink:href="iconName"/></svg></template><script>// doc: https://panjiachen.github.io/vue-element-admin-site/feature/component/svg-icon.html#usageimport{ isExternal}from'@/utils/validate'exportdefault{
name:'SvgIcon',
props:{
iconClass:{
type: String,
required:true},
className:{
type: String,default:''}},
computed:{isExternal(){returnisExternal(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><stylescoped>.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>
在阿里巴巴矢量库中下载svg
使用:
<icon-svgclass="文件名">
每天进步一点,加油!