技术文摘
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 来美化界面,提升用户体验。
- Redis 与 Lua 助力分布式缓存更新功能开发方法
- MySQL 与 Java 实现简单日历功能的方法
- MySQL与Go语言助力开发简易在线投资平台的方法
- MySQL 中用 JavaScript 编写自定义存储过程、触发器与函数的方法
- MongoDB 中数据索引与查询优化功能的实现方法
- PHP在MySQL中实现数据增删改查功能的方法
- 基于MySQL与Java开发简易在线旅游预订系统的方法
- Swift 与 Redis 实现实时聊天功能的开发方法
- 用MySQL与Ruby打造简单投票系统的方法
- Redis与PowerShell在分布式文件存储功能开发中的运用
- 用Redis与Objective-C实现实时地理位置跟踪功能的方法
- MySQL与Java实现简单视频分享功能的方法
- 基于地理位置的应用系统开发:MongoDB 使用指南
- Redis 与 Scala 助力开发缓存预热功能的方法
- 用MySQL与Ruby on Rails开发简易留言板功能的方法