【教程】Vue2中使用svg矢量图

1.npm导包

java 复制代码
npm i svg-sprite-loader --save

2.创建目录放入svg文件,创建SvgIcon.js

3.SvgIcon.js

javascript 复制代码
const req = require.context('./svg', false, /\.svg$/)
const requireAll = requireContext => requireContext.keys().map(requireContext)
requireAll(req)

4.vue.config.js文件中配置

javascript 复制代码
const path = require('path');

module.exports = {
			chainWebpack(config) {	        
	        config.module
	        .rule('svg')
	        .exclude.add(path.resolve(__dirname, 'src/icons'))
	        .end()
	        config.module
	        .rule('icons')
	        .test(/\.svg$/)
	        .include.add(path.resolve(__dirname, 'src/icons'))
	        .end()
	        .use('svg-sprite-loader')
	        .loader('svg-sprite-loader')
	        .options({
	            symbolId: 'icon-[name]'
	        })
	        .end()
	    }
 }

5.在src/compoments/SvgIcon下创建SvgIcon.vue

java 复制代码
<template>
  <svg :class="svgClass" aria-hidden="true">
    <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>

6.main.js

java 复制代码
import './icons/SvgIcon.js' //vue中使用svg
import SvgIcon from './components/SvgIcon/SvgIcon.vue'//vue中使用svg
Vue.component('svg-icon', SvgIcon)//vue中使用svg

7.使用方法

java 复制代码
<template>
  <div>
    <svg-icon class-name="xxxx" icon-class="xxxx"/>
  </div>
</template>
 
<script>
 
export default {
  name: 'test',
}
</script>
 
<style>
  .star-icon {
    font-size: 30px;
    color: gold;
  }
</style>

8.红框里的就是svg-icon效果

相关推荐
有同事要进步4 小时前
LeetCode 14. 最长公共前缀:纵向扫描一次讲透
开发语言·python
猪猪拆迁队4 小时前
跨电脑复制共享-局域网直连踩坑
前端·后端·go
静默回滚4 小时前
逐帧处理视频的内存去哪了,我从看错读数查到没排队
前端
修船大队长4 小时前
CanNm 从休眠唤醒后重复消息报文的周期与数量分析
开发语言·php
事圆则缓4 小时前
Kotlin 变量与函数:把页面状态和行为写成清楚的契约
android·开发语言·kotlin
silvamux_5 小时前
豆包 API 调用教程:Python 接入可跑通示例
开发语言·python
重庆穿山甲5 小时前
我们不做「看起来很聪明」的知识库:一套企业级 RAG 平台的 37 屏真机实录
前端
风花一世月5 小时前
🛩️ 我把一段夕阳飞行做成了能按键驾驶的网页(24 秒四段航线,在线直接玩)
前端
用户11481867894845 小时前
实现一个「配置驱动」的动态表格组件(Vue + Element UI)
前端
希洛兔5 小时前
里氏替换原则详解:子类必须能透明替换基类(含继承风险演示 + 正确重构 + JDK 案例)
java·里氏替换原则