技术文摘
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 来美化界面,提升用户体验。
- Windows 中 Nginx 的启动、停止与重启命令操作流程
- Linux 端口开放查看方法全解析
- Windows Server 2022 内核参数的注册表修改方法
- 网页 502 Bad Gateway nginx/1.20.1 报错成因及解决之道
- Linux 下基于 socket 实现 TCP 服务端的示例代码
- Nginx 403 错误的解决之道
- Nginx 正向代理助力局域网电脑访问外网的详细过程
- Apache Doris 基础概述
- Windows Server 2022 组策略(gpedit.msc)设置大全
- Linux 启动 Nacos 的详细步骤解析
- .net Framework 3.5 安装报错:请求添加或删除指定服务器功能失败的解决办法
- Linux 系统资源查看常用命令分享
- Linux 防火墙配置全流程
- IIS 报错:修改配置或 web.config 提示无法使用此配置节的解决之道
- ASP 网站提示 500 错误的成因及解决之道