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

相关推荐
程序员爱钓鱼3 分钟前
Rust 切片 Slice 详解:安全访问连续数据
前端·后端·rust
要开心吖ZSH1 小时前
一文搞懂:JDK 21 虚拟线程 vs N种异步方案,到底该怎么选?
java·数据库·jdk·虚拟线程
alexander0682 小时前
CSS 类选择器组合
前端·css
-银雾鸢尾-4 小时前
C#中的拓展方法
开发语言·c#
guodingdingh6 小时前
软件开发工作问题总结0718
java·开发语言·数据库
寅时码7 小时前
React 之死·终章:一个 useRef,把闭包陷阱、依赖数组、漫天 rerender 全送走
前端·react.js·ai编程
不好听6137 小时前
HTML 事件监听机制:从 DOM Level 0 到 React 合成事件
前端·react.js·html
wordbaby8 小时前
为什么刷新页面就 404?聊聊 SPA 路由与 Nginx 的那点事
前端
daols888 小时前
vxe-table 渲染器教程一:实现金额输入控件
javascript·vue.js·vxe-table
咖啡八杯8 小时前
GoF设计模式——解释器模式
java·后端·spring·设计模式