Search code examples
dynamicvue.jsimagesource

Image not loading in vue.js


I am trying to dynamically generate images in my vue.js project by creating a basic method:

  methods: {
    changeLang(la
    getImg(image, ext) {
      return '~@/assets/images/' + image + '.' + ext;
    },
      ...

Each component will have it's images generated dynamically:

data () {
    return {
      cat:'frenchcat',
      ...

The following line should identify the method, image and date and convert it into the image URL

<img v-bind:src="getImg(cat, 'svg')" v-bind:alt=cat>

But for some reason the source code simply returns:

<img data-v-61dd7a3d src="~@/assets/images/frenchcat.svg" alt="frenchcat"/>

Why is ~@/assets/ not being converted into an URL path?


Solution

  • You need to use require with v-bind:src:

    getImg(image, ext) {
          return require(`~@/assets/images/${image}.${ext}`);
    }
    

    Unsure if ~ before @ is needed.