VueJS images from json won´t render

Viewed 78

I´ve got a JSON file like this:

"images": {
      "thumbnail": "./assets/starry-night/thumbnail.jpg",
      "hero": {
        "small": "./assets/starry-night/hero-small.jpg",
        "large": "./assets/starry-night/hero-large.jpg"
      },
      "gallery": "./assets/starry-night/gallery.jpg"
    }

My code in Vue is:

<img
          v-bind:src="data.images.thumbnail"
          alt=""
          srcset=""
          height="100px"
          width="100px"
        />

And it "works", it gives back an IMG. But the path of the image is ./assets/starry-night/gallery.jpg and I think that´s why it won´t load.

Do I have to trick the router or anything?

./assets/starry-night/gallery.jpg

Output in Chrome.

2 Answers

Your data is treated as a string, therefore it's looking for the path which of course doesn't exists. Just define a const publicUrl = 'http://mysite.test/' somewhere to complete the image URL such as

<img
    v-bind:src="publicUrl + data.images.thumbnail"
    alt=""
    srcset=""
    height="100px"
    width="100px"
/>

In addition, you can reference a folder by doing

<img src="@/assets/starry-night/thumbnail.jpg"/>

Solved with:

 created() {
    this.publicURL = "https://6e222.csb.app";
  },

And moved assets/xxx/ to PUBLIC folder instead of in SRC.

Related