- src/icons/svg-------->你需要的svg图标
- src/components------->创建 SvgIcon/index.vue(相当于创建一个组件) 复制代码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<template> <svg class="svg-icon" aria-hidden="true"> <use :xlink:href="iconName"></use> </svg> </template> <script setup> import { defineProps, computed } from 'vue' const props = defineProps({ icon: { type: String, required: true } }) const iconName = computed(() => { return `#icon-${props.icon}` }) </script> <style scoped> .svg-icon { width: 1em; height: 1em; vertical-align: -0.15em; fill: currentColor; overflow: hidden; } </style>
- 创 src/icons/index.js ------->将svg图标抛出引用(将svg和那个组件抛出) 复制代码1
2
3
4
5
6
7
8
9
10
11
12
13
14// 组件 import SvgIcon from '@/components/SvgIcon' // svg // 三个参数:引入资源的目录 是否需要便利子目录 匹配文件的规则 const svgRequired = require.context('./svg', false, /.svg$/) // svgRequired.keys()返回的是路径的数组,forEach遍历每个路径 svgRequired.keys().forEach((item) => svgRequired(item)) // 将组件全局引入 export default (app) => { app.component('svg-icon', SvgIcon) }
- main.js引入svg 复制代码1
2
3import SvgIcon from '@/icons' const app = createApp(App) SvgIcon(app)
- 安装loader 复制代码1
npm i --save-dev svg-sprite-loader@6.0.9
- 修改webpack配置 复制代码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
44
45
46
47
48
49
50
51
52
53
54
55const path = require('path') function resolve(dir) { return path.join(__dirname, dir) } const webpack = require('webpack') module.exports = { chainWebpack(config) { // 设置 svg-sprite-loader // config 为 webpack 配置对象 // config.module 表示创建一个具名规则,以后用来修改规则 config.module // 规则 .rule('svg') // 忽略 .exclude.add(resolve('src/icons')) // 结束 .end() // config.module 表示创建一个具名规则,以后用来修改规则 config.module // 规则 .rule('icons') // 正则,解析 .svg 格式文件 .test(/.svg$/) // 解析的文件 .include.add(resolve('src/icons')) // 结束 .end() // 新增了一个解析的loader .use('svg-sprite-loader') // 具体的loader .loader('svg-sprite-loader') // loader 的配置 .options({ symbolId: 'icon-[name]' }) // 结束 .end() config .plugin('ignore') .use( new webpack.ContextReplacementPlugin(/moment[/\]locale$/, /zh-cn$/) ) 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() } }
最后
以上就是酷炫萝莉最近收集整理的关于vue3.2 引入svg图像的全部内容,更多相关vue3.2内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复