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

相关推荐
alsmile2 小时前
AI友好的可视化图形引擎自我革命:Meta2d.js 2.0 历时一年全新重写,性能与多人协作全面升级
前端·开源·数据可视化
行思理2 小时前
Nginx 跨站请求(CORS)配置完全指南:从原理到生产实践
java·前端·nginx
小溪学编程2 小时前
Spring @Bean 与 @Component 注解的区别详解
java·后端·spring
粥里有勺糖2 小时前
视野修炼-技术周刊第137期 | 编程已经面目全非
前端·github·ai编程
IT_陈寒3 小时前
Python的列表推导式用不好真的会爆内存你知道吗
前端·人工智能·后端
Wang's Blog3 小时前
Java 项目实战: 交友项目 - 圈子互动章总结与自检清单
java·bootstrap·交友
moshuying3 小时前
块扩散 + GDN 改造:Clover 把「并行生成」塞进了 Agent 的长上下文里
前端·算法
kyriewen3 小时前
我算了笔账:AI 编程工具一年烧掉两台 MacBook
前端·人工智能·程序员
云和数据.ChenGuang3 小时前
Python 常见特殊方法详解:__new__、__init__、__del__、__str__、__repr__ 与 __getattribute__
开发语言·人工智能·python·1024程序员节
xyouyuweizhu3 小时前
字节流与字符流:Java IO 的两条主线该怎么选
java·开发语言·python