项目中使用svg图标
组件使用方法
module.exports = {
chainWebpack: (config) => {
// set svg-sprite-loader
config.module
.rule('svg')
.exclude.add(path.join(__dirname, '/assets/svg')) // 存放svg文件的目录
.end();
config.module
.rule('icons')
.test(/\.svg$/)
.include.add(path.join(__dirname, '/assets/svg')) // 存放svg文件的目录
.end()
.use('svg-sprite-loader')
.loader('svg-sprite-loader')
.options({
symbolId: 'icon-[name]'
})
.end();
}
}
- 创建组件
在你项目对应的目录创建SvgIcon组件
<template>
<svg
:class="svgClass"
aria-hidden="true"
>
<use :xlink:href="iconName" />
</svg>
</template>
<script>
export default {
name: 'SvgIcon',
props: {
iconClass: { // 这里就是svg文件的名称
type: String,
required: true,
},
className: {
type: String,
default: '',
},
},
computed: {
iconName () { // 利用计算属性拼接生成svg名称
return `#icon-${this.iconClass}`;
},
svgClass () {
if (this.className) {
return 'svg-icon ' + this.className;
} else {
return 'svg-icon';
}
},
},
};
</script>
<style scoped>
.svg-icon {
width: 100%;
height: 100%;
vertical-align: -0.15em;
fill: currentColor;
overflow: hidden;
}
</style>
import Vue from 'vue';
import SvgIcon from '/base/components/SvgIcon/index.vue'; // svg组件
// 注册到全局
Vue.component('SvgIcon', SvgIcon);
// 注册对应的svg图标
const requireAll = (requireContext) => requireContext.keys().map(requireContext);
/**
* 第一个参数 对应的目录
* 第二个参数 是否开启子目录
* 匹配的文件
*/
const req = require.context('./', false, /\.svg$/);
requireAll(req);
// console.log('req', requireAll(req));
- 在main.js使用
import './icons/index.js';
- 使用svg图标
<template>
<div class="container">
<div class="notAuth-container">
<div class="svgContainer">
<!-- notPer 就是svg文件名称 -->
<SvgIcon icon-class="notPer" />
</div>
<div class="text">
暂无权限!
</div>
</div>
</div>
</template>
最终渲染结果