Reputation: 209
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
Upvotes: 0
Views: 1189
Reputation: 4102
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"
>
Upvotes: 1
Reputation: 309
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'
}
}
Upvotes: 0