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 来美化界面,提升用户体验。

TAGS: Vue3 使用方法 SVG Vue-CLI4

欢迎使用万千站长工具!

Welcome to www.zzTool.com