【发布时间】:2021-12-10 06:24:21
【问题描述】:
我从 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 后,我遇到了一个错误“未捕获的 ReferenceError:require is not defined”。我的文件现在使用脚本设置语法,如下所示:
<script setup>
const props = defineProps({
imagePath: { type: String },
})
</script>
<template>
<img :src="require(`@/assets/${props.imagePath}`)"/>
</template>
我尝试了什么
我已经尝试使用相对路径直接从资产文件夹中导入文件,并且成功了。但是我不能用 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>
我错过了什么吗?也许有一个插件可以帮助我实现这一点?
【问题讨论】:
标签: javascript vue.js vite