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

相关推荐
半梦半醒*1 分钟前
zabbix安装
linux·运维·前端·网络·zabbix
大怪v36 分钟前
【搞发🌸活】不信书上那套理论!亲测Javascript能卡浏览器Reader一辈子~
javascript·html·浏览器
清羽_ls37 分钟前
React Hooks 核心规则&自定义 Hooks
前端·react.js·hooks
你的人类朋友43 分钟前
“签名”这个概念是非对称加密独有的吗?
前端·后端·安全
西陵1 小时前
Nx带来极致的前端开发体验——任务缓存
前端·javascript·架构
南尘NCA86661 小时前
企业微信防封防投诉拦截系统:从痛点解决到技术实现
java·网络·企业微信
ONE_PUNCH_Ge1 小时前
Go 语言变量
开发语言
幼稚园的山代王1 小时前
go语言了解
开发语言·后端·golang
晚风残1 小时前
【C++ Primer】第六章:函数
开发语言·c++·算法·c++ primer
Panda__Panda1 小时前
docker项目打包演示项目(数字排序服务)
运维·javascript·python·docker·容器·c#