Home > Blockchain >  Unable to insert data from api as img src in vue js
Unable to insert data from api as img src in vue js

Time:11-11

I'm currently trying to insert data retrieved from an api in to the html on my vue.js (3) project. So far this is my code:

    <template>
    <div id="cocktails">
    <div >
        <img src="{{ data.drinks[0].strDrinkThumb }}" />
        <h1>{{ data.drinks[0].strDrink }}</h1>
        <h6>{{ data.drinks[0].strDrinkThumb }}</h6>
    </div>

    <div >
       <h1>{{ datatwo.drinks[0].strDrink }}</h1>
    </div>
    </div>
</template>

    <script setup>
    import { ref } from 'vue';
    const data = ref(null);
    const datatwo = ref(null);
    const error = ref(null);
    
    fetch('https://www.thecocktaildb.com/api/json/v1/1/random.php')
      .then((res) => res.json())
      .then((json) => (data.value = json))
      .catch((err) => (error.value = err));
      console.log(data)
    fetch('https://www.thecocktaildb.com/api/json/v1/1/random.php')
      .then((res) => res.json())
      .then((json) => (datatwo.value = json))
      .catch((err) => (error.value = err));
    

    </script>

I'm doing several fetch requests because I'm wanting several different random results from the api. at the top, I add my img src {{ data.drinks[0].strDrinkThumb }} however, when I load the page, it shows a tiny image icon and when I inspect the page and go to the html, the source literally just shows "{{ data.drinks[0].strDrinkThumb }}" whereas for the it is correctly replacing it with the string that my fetch response contained (a URL).

I can't seem to figure out why it's working for the but not the image source. All help is much appreciated, thanks!

CodePudding user response:

try using one of the below

<img :src="data.drinks[0].strDrinkThumb" />

OR

<img :src="require(data.drinks[0].strDrinkThumb)" />
  • Related