[英]Using import/require in Vue.js data property with dynamic value
我正在嘗試將隨機圖像(image-01.jpg、image-02.jpg、... image-05.jpg)添加到我在 Vue.js 中與data
選項一起使用的import
/ require
請求,代碼如下所示:
<script>
const randomImage = `image-0${(Math.floor(Math.random() * 5) + 1)}.jpg`
export default {
data () {
return {
image: import('@/some/module/in/some/folder/\'' + randomImage + '\'')
}
}
}
</script>
但我得到的錯誤輸出是:
Error: Cannot find module './'image-03.jpg'' at eval (eval at ./some/module/in/some/folder lazy recursive ^\\.\\/'.*'$
有沒有辦法實現這一目標?
提前謝謝了。
Ps我也試過以下方法:
<script>
const randomImage = `@/some/module/in/some/folder/winter-0${(Math.floor(Math.random() * 5) + 1)}.jpg`
export default {
data () {
return {
image: import(`${randomImage}`)
}
}
}
</script>
但得到類似的錯誤。
Pps 我還應該補充一點,我已經嘗試過使用require
而不是import
。
要對此進行更新(我不確定這是“正確”的做法).. 下面的代碼示例現在可以工作了。
<template>
<img
alt="Random image"
:src="image"
/>
</template>
<script>
const randomImage = `image-0${(Math.floor(Math.random() * 5) + 1)}`
export default {
data () {
return {
image: null
}
},
mounted () {
import('@/some/module/folder/' + randomImage + '.jpg').then((image) => {
if (image.default) {
this.image = image.default
}
})
}
}
</script>
如果有人有更優雅的解決方案,請告訴我。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.