在 Vue3 和 Vite 中动态加载 SVG

dynamically loading SVG in Vue3 and Vite

我正在尝试将我的 Vue2/Webpack 应用程序转换为 Vue3/Vite。

在 Vue2/Webpack 中有效:

<div v-html="require('!!html-loader!../../assets/icons/' + this.icon + '.svg')"></div>

Html-loader 添加了:

"html-loader": "1.3.2",

在 Vue3/Vite 中抛出错误:ReferenceError: require is not defined

我四处寻找执行此操作的示例,但不知道如何在编译时不知道文件名的情况下执行此操作。这可能吗?

你可以看看 vite-svg-loader 插件,并将 SVG 文件加载为 Vue 组件。

您还可以将 延迟加载组件 技术与 defineAsyncComponent 来自 Vue3 - ref.

import() 就像 @tony19 在这个 :

中展示的那样
<script>
const getServiceIcon = async iconName => {
  const module = await import(/* @vite-ignore */ `../assets/svg/${iconName}.svg`)
  return module.default.replace(/^\/@fs/, '')
}

export default {
  data() {
    return {
      icon: null,
      iconName: 'icon1', // icon1.svg
    }
  },
  watch: {
    iconName: {
      async handler(iconName) {
        this.icon = await getServiceIcon(iconName)
      },
      immediate: true,
    },
  },
}
</script>

<template>
  <button @click="iconName = 'icon2'">Change to another SVG</button>
  <img :src="icon" height="72" width="72" />
</template>