在 Vue.js 数据 属性 中使用具有动态值的 import/require

Using import/require in Vue.js data property with dynamic value

我正在尝试将随机图像 (image-01.jpg, image-02.jpg, ... image-05.jpg) 添加到 import/ require 请求我在 Vue.js 中使用 data 选项,代码如下所示:

<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 ^\.\/'.*'$

有办法实现吗?

非常感谢。


P.s。我还尝试了以下方法:

<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>

但是得到类似的错误。


P.p.s。我还应该补充一点,我尝试使用 require 而不是 import

对此进行更新(我不确定这是 'proper' 的做法)。下面的代码示例现在可以使用了。

<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>

如果有人有更优雅的解决方案,请告诉我。