vite引入svg图片
# 一、安装:
npm i vite-plugin-svg-icons -D
1
# 二、main.js中引入
import 'virtual:svg-icons-register'
1
# 三、引入方法
svg图片路径src/assets/svg/xxx.svg
# 四、vite.config.js配置
import path from 'path'
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'
export default defineConfig({
plugins: [
createSvgIconsPlugin({
// 指定要缓存的文件夹
iconDirs: [path.resolve(process.cwd(), 'src/assets/svg')],
// 指定symbolId格式
symbolId: '[name]'
})
]
})
1
2
3
4
5
6
7
8
9
10
11
12
13
2
3
4
5
6
7
8
9
10
11
12
13
# 五、svg组件封装
src/components/SvgIcon.vue
<script setup>
import { defineProps, computed } from "vue";
const props = defineProps({
name: {
type: String,
required: true
},
color: {
type: String,
default: ''
},
size: {
type:[Number,String],
default: 14
}
})
const iconName = computed(() => `#${props.name}`)
const svgClass = computed(() => {
console.log(props.name, "props.name")
if (props.name) {
return `svg-icon ${props.name}`
}
return "svg-icon"
})
</script>
<template>
<svg :class="svgClass" :style="{
width: size + 'px',
height: size + 'px'
}"
>
<use :xlink:href="iconName" :fill="color" />
</svg>
</template>
<style scoped>
.svg-icon {
fill: currentColor;
vertical-align: middle;
}
</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
31
32
33
34
35
36
37
38
39
40
41
42
43
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
31
32
33
34
35
36
37
38
39
40
41
42
43
# 六、全局引入组件
import svgIcon from './components/SvgIcon.vue'
createApp(App).component('svg-icon',svgIcon).use(router).use(ElementPlus).mount('#app')
1
2
3
2
3
# 七、局部引入
Home.vue
<script setup>
import svgIcon from '../components/SvgIcon.vue'
</script>
<template>
<SvgIcon name="operationManage" color="red"></SvgIcon>
</template>
1
2
3
4
5
6
7
2
3
4
5
6
7
上次更新: 2024/02/20, 17:31:36
- 02
- Node与GLIBC_2.27不兼容解决方案08-19
- 03
- Git清空本地文件跟踪缓存08-13