1.首先插件依赖安装

npm i svg-sprite-loader

2.loader配置,在vue.config.js中配置

*主要是chainWebpack和configureWebpack中的配置(所有的svg图片放在src/assets/svg文件夹中)

const { defineConfig } = require("@vue/cli-service");

const path = require("path");

module.exports = defineConfig({

transpileDependencies: true,

chainWebpack: function (config) {

config.module.rule('svg').exclude.add(path.resolve(__dirname, './src/assets/svg')).end()

},

configureWebpack: {

module: {

rules: [

{

test: /\.svg$/,

loader: 'svg-sprite-loader',

include: path.resolve(__dirname, './src/assets/svg'),

options: { symbolId: 'icon-[name]' }

}

]

}

},

});

3.在components创建SvgIcon.vue组件

4.在src目录下创建svgPlugin.ts,对SvgIcon.vue组件的处理

//引入svgicon组件

import SvgIcon from "@/components/SvgIcon.vue";

const componentsvgPlugin: any = {

install: function(vue: any, options: any) {

if (

options &&

options.imports &&

Array.isArray(options.imports) &&

options.imports.length > 0

) {

// 按需引入svg图标

const { imports } = options;

imports.forEach((name: any) => {

require(`@/assets/svg/${name}.svg`);

});

} else {

// 全量引入svg图标

const ctx = require.context("@/assets/svg", false, /\.svg$/);

ctx.keys().forEach(path => {

const temp = path.match(/\.\/([A-Za-z0-9\-_]+)\.svg$/);

if (!temp) return;

const name = temp[1];

require(`@/assets/svg/${name}.svg`);

});

}

vue.component('SvgIcon', SvgIcon);

}

};

export default componentsvgPlugin;

5.全局引用,在main.ts中引用

import svgPlugin from "./svgPlugin";

app.use(svgPlugin, {

imports: []

})

6.最后就可以在需要的组件中使用了

效果图:

 项目目录:

 

 

相关链接

评论可见,请评论后查看内容,谢谢!!!
 您阅读本篇文章共花了: