我从 Vue CLI 切换到 Vite CLI ,从 Vue 3 的 Composition API 切换到 SFC Script setup API。
它以前对我有用
当我使用官方 Vue CLI 时,我可以通过 props 传递路径的文件名来导入图像源:
<template>
<img :src="require(`@/assets/${imagePath}`)"/>
<template/>
<script>
export default {
props: {
imagePath: { type: String },
},
setup() {
// ...
}
}
<script/>
然后这样称呼它:
<template>
<Image imagePath="icon.png" />
</template>
迁移到 Vite 后出现的错误
但是自从我迁移到 Vite CLI 后,出现了“Uncaught ReferenceError: require is not defined”的错误。我的文件现在使用脚本设置语法,如下所示:
<script setup>
const props = defineProps({
imagePath: { type: String },
})
</script>
<template>
<img :src="require(`@/assets/${props.imagePath}`)"/>
</template>
我试过的
我已经尝试使用相对路径直接从 assets 文件夹导入文件,并且成功了。但是我无法使用 import 语句指定 props 的路径。
<script setup>
// Works but do not use the props, so the component is not reusable
import logo from "./../assets/logo.png"
</script>
<template>
<img :src="logo"/>
</template>
<script setup>
// Component is reusable but the import statement has illegal argument I guess
const props = defineProps({
imagePath: { type: String },
})
import logo from `./../assets/${props.imagePath}`
</script>
<template>
<img :src="logo"/>
</template>
我也在模板中尝试了 import 语句,但它甚至无法编译代码:
<script setup>
const props = defineProps({
imagePath: { type: String },
})
</script>
<template>
<img :src="import `./../assets/${props.iconPath}`" />
</template>
我错过了什么吗?也许存在一个插件可以帮助我实现这一目标?
原文由 Dony 发布,翻译遵循 CC BY-SA 4.0 许可协议
我也遇到了这个问题。我搜索了这个并根据这个 github问题评论 找到了,
有关此 功能的更多信息 | Vite - 静态资源
通过一些搜索,我找到了这个对我有用的 Vue 3 代码示例 链接