0

I'm trying to add a random image (image-01.jpg, image-02.jpg, ... image-05.jpg) to an import/require request that I'm using with the data option in Vue.js, the code looks like this:

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

But the error output I'm getting is:

Error: Cannot find module './'image-03.jpg'' at eval (eval at ./some/module/in/some/folder lazy recursive ^\.\/'.*'$

Is there a way to achieve this?

Many thanks in advance.


P.s. I've also tried the following:

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

But get a similar error.


P.p.s. I should also add that I've tried using require instead of import.

Neil Merton
  • 553
  • 4
  • 17
  • Are you going to use this image in your template? – Nitheesh Dec 16 '19 at 10:02
  • Does this answer your question? [Dynamically import images from a directory using webpack](https://stackoverflow.com/questions/42118296/dynamically-import-images-from-a-directory-using-webpack) – Fraction Dec 16 '19 at 10:12
  • @Nitheesh - yes, I will be using the `image` value in my `` tag. – Neil Merton Dec 16 '19 at 10:34
  • @Fraction - I'll have a look through the answers given in the link you've provided. If I find something that works I'll update here with the solution. – Neil Merton Dec 16 '19 at 10:35

1 Answers1

0

To update on this (and I'm not sure this is the 'proper' way of doing it).. the code example below now works.

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

If anyone has a more elegant solution then please let me know.

Neil Merton
  • 553
  • 4
  • 17
  • I found the information in this link quite useful, in case anyone else runs into a similar problem: https://github.com/webpack/webpack/issues/4292 – Neil Merton Dec 16 '19 at 11:13