【教程】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效果

相关推荐
2601_9498144915 小时前
Spring Boot中使用Server-Sent Events (SSE) 实现实时数据推送教程
java·spring boot·后端
splage15 小时前
HeidiSQL导入与导出数据
java
热爱Java,热爱生活15 小时前
浅谈Spring三级缓存
java·spring·缓存
ConardLi15 小时前
把 Claude Design 做成 Skill,你的网站也能拥有顶级视觉体验
前端·人工智能·后端
星越华夏15 小时前
python——三角函数用法
开发语言·python
代码中介商15 小时前
C语言数据存储深度解析:从原码反码补码到浮点数存储
c语言·开发语言·内存
@ chen15 小时前
IDEA初始化配置
java·ide·intellij-idea
We་ct15 小时前
LeetCode 120. 三角形最小路径和:动态规划详解
前端·javascript·算法·leetcode·typescript·动态规划
wellc16 小时前
SpringBoot集成Flowable
java·spring boot·后端
IT_陈寒16 小时前
React状态更新那点事儿,我掉坑里爬了半天
前端·人工智能·后端