在Vue3和Vite中动态加载SVG

Pau*_*lie 4 javascript vue.js vuejs3 vite

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

在 Vue2/Webpack 中,这是有效的:

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

Html-loader 添加了:

"html-loader": "1.3.2",
Run Code Online (Sandbox Code Playgroud)

在 Vue3/Vite 中,这会引发错误:ReferenceError: require is not defined

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

JEd*_*dot 5

您还可以使用带有from - ref 的延迟加载组件技术defineAsyncComponentVue3

或者@tony19在这个答案import()中显示了类似的内容:

<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>
Run Code Online (Sandbox Code Playgroud)