How to display images from an array in vuepress or vuejs?

Viewed 181

I have an array which looks like below:

  questions: [
    {
      question: "How do you say 'My Car' in Malayalam",
      answers: {
        a: "a) Ente Car",
        b: "b) Ninte/Ningalude Car",
        c: "c) Onte Car",
        d: "d) Aarudeyo Car",
      },
      images: "@alias/vallamkali.jpg",
      correctAnswer: "a",
    },
    {
      question: "How do you say 'your Car' in Malayalam",
      answers: {
        a: "a) Onte Car",
        b: "b) Aarudeyo Car",
        c: "c) Ninte/Ningalude Car",
        d: "d) Ente Car",
      },
      images: "@alias/il_leki.png",
      correctAnswer: "c",
    },
    {
      question: "How do you say 'our car' in Malayalam",
      answers: {
        a: "a) Achante Car",
        b: "b) Ninte/Ningalude Car",
        c: "c) Ente Car",
        d: "d) Nammalude/Njangalude Car",
      },
      images: "@alias/isthapetta_doubt.jpg",
      correctAnswer: "d",
    },
  ],

but when I try to print using the below code

        <div v-if="index < count">
          <p>{{ questions[index]['question']}}</p>
          <p>{{ questions[index]['images']}}</p
        </div>

Only the questions are generated correctly but the images are not displayed properly, only the location gets printed as below and is highlighted in blue. Please help.

Image not displayed only address

2 Answers

You can not display images in p tag You need to make method or computed property (assuming images = il_leki.png):

methods: {
  getImg(img) {
    return require(`@alias/${img}`);
  }
}

then in template call that method in img tag (instead p tag) passing img :

<img :src="getImg(questions[index]['images']) />

I didn't use the function call. I directly used require keyword in the img tag itself and it worked.

<img :src="require(`@alias/${questions[index]['images']}`)" alt="No image here too" />

@Nikola Pavicevic - Thanks for helping me think in this direction!

Related