技术文摘
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 来美化界面,提升用户体验。
- nginx 参数与变量的配置方法
- Nginx 中对同一 IP 特定 URL 访问的限流实现
- Centos7 安装 Nginx 后 conf.d 目录及 default.conf 文件缺失问题的解决
- Ubuntu 环境下 Nginx 安装部署详细步骤(有网)
- Linux 终端执行 shell 脚本权限不足的问题与解决之道
- Nginx 前端项目 location 中 root 与 alias 配置指南
- Linux 中 boost 库的编译与安装方法
- Windows 系统中 Nginx 的安装与部署详细教程(涵盖多个站点)
- Linux 内核启动流程中 start_kernel 相关问题
- Linux 中利用 date 命令获取系统时间的方法
- Linux 系统调用相关问题
- Windows Server 2016 DNS 服务搭建方法与步骤(图文)
- Nginx 多 IP 部署多站点的实现流程
- nginx 解决 Access-Control-Allow-Origin 问题的方法
- 解决 Linux “unable to locate package”问题