- 下载依赖
npm install svg-sprite-loader --save
- 创建svg目录
- 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() { console.log('this.className') console.log(this.className) if (this.className) { return 'svg-icon ' + this.className } else { return 'svg-icon' } }, }, } </script> <style scoped> .svg-icon { } </style>
- index.js
//下面这个是导入svgIcon/svg下的所有svg文件 const requireAll = requireContext => requireContext.keys().map(requireContext) /* 第一个参数是:'./svg' => 需要检索的目录, 第二个参数是:false => 是否检索子目录, 第三个参数是: /\.svg$/ => 匹配文件的正则 */ const req = require.context('./svg', false, /\.svg$/) requireAll(req);
- main.js
// svg import '@/components/svgIcons/index.js' import SvgIcon from '@/components/svgIcons/index.vue'// svg组件 const app = createApp(App) app.component('svg-icon', SvgIcon);
- vue.config.js
module.exports = { // svg chainWebpack: (config) => { //配置 svg-sprite-loader // 第一步:让其他svg loader不要对src/icons进行操作 config.module .rule('svg') .exclude.add(resolve('src/components/svgIcons/svg'))//注意:路径要具体到存放的svg的路径下,不然会报错 .end() // 第二步:使用svg-sprite-loader 对 src/icons下的svg进行操作 config.module .rule('icons') .test(/\.svg$/) .include.add(resolve('src/components/svgIcons/svg'))//注意:路径要具体到存放的svg的路径下,不然会报错 .end() .use('svg-sprite-loader') .loader('svg-sprite-loader') .options({ symbolId: 'icon-[name]' }) .end() } };
- 使用
<svg-icon icon-class="projectObjLenged" class="projectLengedImg" />