简体   繁体   English

Vue / Vuetify 动态绑定来自 api 的图像

[英]Vue / Vuetify bind image from api dynamically

I want to bind an image dynamically to my <v-img> component.我想将图像动态绑定到我的<v-img>组件。

<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.该请求有效,我成功获得了有效的图像 url。 But I am unable to bind it to my image src.但我无法将它绑定到我的图像 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:第一个数据需要在vue中返回一个object:

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

Second of all you need to call the setBgImg() method using this :其次,您需要使用this方法调用setBgImg()方法:

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

After that you should be able to show the given image from the api:之后,您应该能够显示来自 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如果您从 Chrome 开发工具的控制台检查,您应该会看到一些基于上面代码的错误,即 this.backgroundImage 未定义

The data () method should return an object data() 方法应该返回一个 object

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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