vue2项目 使用 svg

项目中使用svg图标
组件使用方法

  1. 安装svg
    npm install svg-sprite-loader -D
  2. 添加编译配置
    在vue.config.js添加一下配置
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();
  }
}
  1. 创建组件

在你项目对应的目录创建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>
  1. 注册svg图标
    在src目录下创建icons文件,所有的.svg文件都放这个文件
    另外在icons文件下创建index.js文件写入下面的代码
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));
  1. 在main.js使用
import './icons/index.js';
  1. 使用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>

最终渲染结果

在这里插入图片描述

相关文章

显卡天梯图2024最新版,显卡是电脑进行图形处理的重要设备,...
初始化电脑时出现问题怎么办,可以使用win系统的安装介质,连...
todesk远程开机怎么设置,两台电脑要在同一局域网内,然后需...
油猴谷歌插件怎么安装,可以通过谷歌应用商店进行安装,需要...
虚拟内存这个名词想必很多人都听说过,我们在使用电脑的时候...
win11本地账户怎么改名?win11很多操作都变了样,用户如果想要...