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
  • 82,684
  • 19
  • 144
  • 164
Lucas Marra
  • 169
  • 1
  • 16
  • 1
    You can check this solution here: https://stackoverflow.com/questions/37645243/static-image-src-in-vue-js-template – Rodrigo Silva Aug 03 '20 at 21:20
  • 1
    If you load images from another server it is called hot linking and must be allowed on your server. But it will work by default in apache/nginx i think. So you only need to check that the other server can access the image resources. – NoNickAvailable Aug 03 '20 at 21:20
  • @RodrigoVinicius this and Majed comment helped me alot! – Lucas Marra Aug 03 '20 at 21:21

2 Answers2

1

You need to bind the image name to the src:

<img :src="`./img/products/${potion.image}`" />
Majed Badawi
  • 27,616
  • 4
  • 25
  • 48
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
  • 82,684
  • 19
  • 144
  • 164