Vue3 Vue CLI 中引入 SVG图标
# Vue3 Vue CLI 中引入 SVG图标
# 1. 使用 svg-sprite-loader
在 Vue CLI 中,你可以通过 svg-sprite-loader 插件来处理 SVG 图标。
# 2. 安装依赖
npm install svg-sprite-loader -D
1
# 3. 配置 vue.config.js
vue.config.js 是 Vue CLI 项目的配置文件,添加 svg-sprite-loader 配置来处理 SVG 图标。
const path = require('path');
module.exports = {
chainWebpack: (config) => {
// 清除默认的 svg 处理规则
config.module
.rule('svg')
.exclude.add(path.resolve(__dirname, 'src/assets/icons'))
.end();
// 添加 svg-sprite-loader 处理 svg 图标
config.module
.rule('icons')
.test(/\.svg$/)
.include.add(path.resolve(__dirname, 'src/assets/icons'))
.end()
.use('svg-sprite-loader')
.loader('svg-sprite-loader')
.options({
symbolId: 'icon-[name]', // 设置 symbolId 格式
})
.end();
},
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
配置说明:
- 清除默认的 SVG 处理规则:Vue CLI 默认的 SVG 处理规则可能会将所有 SVG 文件作为文件资源加载,我们需要清除这些规则。
- 添加
svg-sprite-loader:将指定目录下的 SVG 图标转换为symbol,并通过<use>标签引用。
# 4. 创建存放 SVG 图标的文件夹
在 src/assets 目录下创建 icons 文件夹,用于存放所有的 SVG 图标。
项目结构示例:
src
├── assets
│ ├── icons
│ │ ├── home.svg
│ │ ├── user.svg
│ │ └── settings.svg
...
1
2
3
4
5
6
7
2
3
4
5
6
7
将所有图标文件放入 src/assets/icons 目录中。
# 5. 创建 SvgIcon 组件
封装一个 SvgIcon.vue 组件,方便在项目中复用 SVG 图标。
<template>
<svg :class="svgClass" aria-hidden="true">
<use :xlink:href="`#icon-${iconName}`"></use>
</svg>
</template>
<script setup>
import { computed } from 'vue';
const props = defineProps({
iconName: {
type: String,
required: true,
},
className: {
type: String,
default: '',
},
});
const svgClass = computed(() => 'svg-icon ' + props.className);
</script>
<style scoped>
.svg-icon {
width: 1em;
height: 1em;
fill: currentColor;
}
</style>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
组件说明:
iconName:图标名称,对应symbolId中的[name]。className:自定义 SVG 图标样式。
# 6. 在 main.js 中全局注册组件
在 src/main.js 中全局注册 SvgIcon 组件。
import { createApp } from 'vue';
import App from './App.vue';
import SvgIcon from '@/components/SvgIcon.vue'; // 引入 SvgIcon 组件
const app = createApp(App);
app.component('svg-icon', SvgIcon);
app.mount('#app');
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
# 7. 在页面中使用 SVG 图标
将 SVG 文件放入 src/assets/icons 目录后,使用时只需指定文件名(不带 .svg 后缀)。
<svg-icon icon-name="home"></svg-icon>
1
编辑此页 (opens new window)