vue中使用svg组件

安装依赖
	npm i -D svg-sprite-loader
1、在src下面建立icon目录,存放svg图标

在这里插入图片描述

2、封装SvgIcon组件

/components/SvgIcon/index.vue

<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: 1rem;
		height: 1rem;
		fill: currentColor;
		overflow: hidden;
	}
</style>

3、在icon文件中建立index.js文件,引入组件
import Vue from 'vue'
import SvgIcon from '@/components/SvgIcon'// svg组件

// register globally
Vue.component('svg-icon', SvgIcon)

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

requireAll(req)
4、在main.js中导入icons/index.js

注意: 不导入icons,直接进行步骤6页面会报错svg-icon没有正确注册

import '@/icons'
5、修改vue.config.js配置

注意: 不配置这一步的话 页面svg是空的,因为没有对.svg文件进行处理

const path = require("path");
const resolve = dir => path.join(__dirname, dir);
	
module.exports = {
	 chainWebpack: config => {
	 	const svgRule = config.module.rule("svg");
	    svgRule.uses.clear();
	    svgRule.exclude.add(/node_modules/);
	    svgRule
	      .test(/\.svg$/)
	      .use("svg-sprite-loader")
	      .loader("svg-sprite-loader")
	      .options({
	        symbolId: "icon-[name]"
	      });
	
	    const imagesRule = config.module.rule("images");
	    imagesRule.exclude.add(resolve("src/icons"));
	    config.module.rule("images").test(/\.(png|jpe?g|gif|svg)(\?.*)?$/);
	 }
};
6、在需要的页面中直接使用
<ul class="wrapflex">
	<li
		class="shadow lh30 blodliner-red"
		@click="toTrade(item)"
	>
		<div>
			<svg-icon v-bind:icon-class="item.varietyType.toUpperCase().replace('USDT', '')"></svg-icon>
		</div>
	</li>
</ul>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值