技术文摘
Vue3 与 Vue-CLI4 中 SVG 的使用方法
2025-01-10 20:45:10 小编
Vue3 与 Vue-CLI4 中 SVG 的使用方法
在 Vue3 和 Vue-CLI4 的项目开发中,SVG(可缩放矢量图形)的运用能为界面增添高质量的图形元素。下面将详细介绍 SVG 在这两者中的使用方法。
一、在 Vue3 项目中使用 SVG
1. 安装必要插件
要在项目中安装 @vueuse/core 库,它提供了一些实用的工具函数来处理 SVG。可以使用 npm 或 yarn 进行安装:
npm install @vueuse/core
# 或者
yarn add @vueuse/core
2. 引入并使用 SVG
在组件中,我们可以通过 @vueuse/core 提供的函数来引入 SVG。例如,在 <script setup> 中:
<template>
<div>
<img :src="svgUrl" alt="SVG Image">
</div>
</template>
<script setup>
import { ref } from 'vue';
import { useSvg } from '@vueuse/core';
const svgUrl = ref('');
const svgPath = 'your-svg-file.svg';
useSvg(svgPath).then((url) => {
svgUrl.value = url;
});
</script>
上述代码中,useSvg 函数用于获取 SVG 文件的 URL,获取成功后将其赋值给 svgUrl,然后在模板中通过 :src 绑定到 img 标签上。
二、在 Vue-CLI4 项目中使用 SVG
1. 配置 vue.config.js
在项目根目录下找到 vue.config.js 文件(如果没有则创建一个),添加如下配置:
module.exports = {
chainWebpack: (config) => {
config.module
.rule('svg')
.exclude.add(/node_modules/)
.end()
.use('vue-svg-loader')
.loader('vue-svg-loader')
.options({
svgo: false
});
}
};
这段配置的作用是告诉 webpack 使用 vue-svg-loader 来处理 SVG 文件,并排除 node_modules 目录。
2. 创建 SVG 组件
在 src/components 目录下创建一个 SvgIcon.vue 组件:
<template>
<svg :class="svgClass" :style="svgStyle" aria-hidden="true">
<use :xlink:href="iconName"></use>
</svg>
</template>
<script setup>
import { ref } from 'vue';
const props = defineProps({
iconClass: {
type: String,
default: ''
},
iconName: {
type: String,
required: true
},
svgStyle: {
type: Object,
default: () => ({})
}
});
const svgClass = computed(() => `svg-icon ${props.iconClass}`);
</script>
<style scoped>
.svg-icon {
width: 1em;
height: 1em;
vertical-align: -0.15em;
fill: currentColor;
overflow: hidden;
}
</style>
3. 使用 SVG 组件
在其他组件中使用 SvgIcon.vue 组件:
<template>
<div>
<SvgIcon iconName="#your-icon-name" iconClass="custom-class" :svgStyle="{ color: 'red' }" />
</div>
</template>
<script setup>
import SvgIcon from '@/components/SvgIcon.vue';
</script>
通过以上步骤,无论是在 Vue3 还是 Vue-CLI4 项目中,都能方便地使用 SVG 来美化界面,提升用户体验。
- Go 语言实现的几种限流算法
- 利用 SVG 打造带标识的 Favicon
- JVM 沙箱安全机制笔记系列
- Nacos 源码中订阅机制的来龙去脉
- 提升 Xenomai 实时性的若干配置建议
- Flink 并行流中 watermark 机制未触发窗口计算的原因剖析
- 可达性分析的深度解析:安全点与安全区域
- ToB 软件质量保障的两年历程
- Go 历经 13 年探讨,如何解决再赋值的陷阱?
- TypeScript 类型挑战:元组到对象的转换
- 一次性讲清令人头疼的分布式事务
- Elasticsearch 引入系统架构计划遭领导坚决反对
- 链路追踪的核心原理及解决方案
- 19 款免费实用的 CSS 代码样式生成工具
- 如何寻觅适合的 Python 库?