简体   繁体   中英

Vue / Vuetify bind image from api dynamically

I want to bind an image dynamically to my <v-img> component.

<template>
  <v-img
    id="image"
    :src=backgroundImage
    aspect-ratio="1"
    class="grey lighten-2"
  >
  </v-img>
</template>

In my script I am loading a default image, on call a route in the mounted methods which gives me randomly an image from a server. The request works and I successfully get an image url which works. But I am unable to bind it to my image src.

<script>
export default {
  data: () => {
    backgroundImage: 'https://hatrabbits.com/wp-content/uploads/2017/01/random.jpg'
  },

  mounted () {
    setBgImg();
  },

  methods: {
    // get random background image 
    async setBgImg() {
      const route = 'http://localhost:4000/api/image/random';
      const { data } = await axios.get(route);

      this.backgroundImage = data[0].image;
    }
  }
}
</script>

Edit forgot to paste the error message, here it is:

> Cannot use 'in' operator to search for 'backgroundImage' in undefined

There are a few things which need an update.

First data needs to return an object in vue:

    export default {
        data: () => ({
        backgroundImage: ''
    }),

Second of all you need to call the setBgImg() method using this :

      mounted () {
        this.setBgImg();
      },

After that you should be able to show the given image from the api:

      <v-img
        id="image"
        :src="backgroundImage"
        aspect-ratio="1"
        class="grey lighten-2"
      >

If you check from console of Chrome Dev Tools, you should see some error based on above code that this.backgroundImage is undefined

The data () method should return an object

data () {
    return {
       backgroundImage: 'https://hatrabbits.com/wp-content/uploads/2017/01/random.jpg'
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM