1

I'm really new to vue and axios and need a really big help.

I have a API returning me some array data.

API:

"potions": {
"1": {
  "id": 1,
  "name": "Aging Potion",
  "image": "aging-potion.png",
  "price": 29.99,
  "effect": "Causes the drinker to advance in age",
  "ingredients": [
    "Red Wine",
    "Prune Juice",
    "Hairy Fungus",
    "Tortoise Shell",
    "Caterpillar",
    "Bat Tongue"
  ]
}

As you can see, image is locally called. I have all the images locally on my machine on ./img/products. How i'm linking all images to correspondent potion in v-for? Is possible to Javascript render images that are not in same server as api data?

HTML code:

 <div id="app">
    <section v-if="errored">
        <p>Pedimos desculpas, não estamos conseguindo recuperar as informações no momento. Por favor, tente
            novamente mais tarde.</p>
    </section>
    <div v-else>
        <div v-for="(potion, index) in potions_list" :key="index">
            <div class="img">

            </div>
            <h1>{{potion.name}}</h1>
            <!-- <p>{{potion.effect}}</p> -->
            <p>{{potion.price}}</p>
            <!-- <div v-for="(ingredient, index) in potion.ingredients" :key="index">
                        <ul>{{ingredient}}</ul>
                    </div> -->
        </div>
    </div>
</div>

JS code:

new Vue({
el: '#app',
data() {
    return {
        potions_list: [],
        errored: false,
    }
},
mounted: function () {
    this.getAllPotions();
},
mounted() {
    axios
        .get('https://cdn.rawgit.com/LucasRuy/1d4a5d45e2ea204d712d0b324af28bab/raw/342e0e9277be486102543c7f50ef5fcf193234b6/potions.json')
        .then((response) => {
            const { potions } = response.data;
            this.potions_list = potions;
            console.log(potions);
        })
        .catch(error => {
            console.log(error)
            this.errored = true
        })
},

})

Boussadjra Brahim
  • 64,851
  • 14
  • 107
  • 134
Lucas Marra
  • 149
  • 1
  • 15

2 Answers2

1

You need to bind the image name to the src:

<img :src="`./img/products/${potion.image}`" />
Majed Badawi
  • 25,448
  • 4
  • 17
  • 37
1

You could concatenate the path with image name coming from API and use require to load them if you're using vue cli or any tool based on a bundler :

<img :src="require('./img/products/'+potion.image)" />
Boussadjra Brahim
  • 64,851
  • 14
  • 107
  • 134