700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > vue中引入本地svg图标

vue中引入本地svg图标

时间:2023-01-28 07:46:06

相关推荐

vue中引入本地svg图标

1.在阿里巴巴图标上下载svg图标到本地
2.在项目里面封装组件

index.vue引入如下代码

<template><svg :class="svgClass" aria-hidden="true" v-on="$listeners"><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'}},styleExternalIcon() {return {mask: `url(${this.iconClass}) no-repeat 50% 50%`,'-webkit-mask': `url(${this.iconClass}) no-repeat 50% 50%`}}}}</script><style scoped>.svg-icon {width: 1.5em;height: 1.5em;vertical-align: -0.15em;fill: currentColor;overflow: hidden;}.svg-external-icon {background-color: currentColor;mask-size: cover!important;display: inline-block;}</style>

3.安装插件npm i svg-sprite-loader --save
4.在项目的src目录下面新建icons>svg文件夹存放下载的svg图标,并在icons文件夹下面新建一个index.js文件,如下图:

在index.js文件里面引入如下代码

import Vue from 'vue'import SvgIcon from '@/components/SvgIcon'// 注册到全局ponent('svg-icon', SvgIcon)const requireAll = requireContext => requireContext.keys().map(requireContext)const req = require.context('./svg', false, /\.svg$/)requireAll(req)

5.在配置vue.config.js文件里面配置如下代码

注意:resolve()里面路径不要写错了,结合自己项目里面的路径!!!

const path = require('path')const resolve = dir => path.join(__dirname, dir)module.exports = {devServer:{port:8099,open:true},chainWebpack: (config) => {config.module.rule("svg").exclude.add(resolve("src/icons")).end();config.module.rule("icons").test(/\.svg$/).include.add(resolve("src/icons")).end().use("svg-sprite-loader").loader("svg-sprite-loader").options({symbolId: "icon-[name]",}).end();},};

6.在main.js里面引入
7.页面引入使用
8.页面展示效果

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。