计算属性" main_image"被分配但没有二传手

时间:2018-04-17 04:04:30

标签: vue.js vuejs2

如何解决此错误" Computed property" main_image"已被分配但没有制定者"

我试图每5秒(随机)切换一次main_image。这是我的代码,请检查created方法和setInterval。

<template>
  <div class="main-image">
    <img v-bind:src="main_image">
  </div>
  <div class="image-list>
    <div v-for="img in images" class="item"><img src="img.image"></div>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  name: 'Item',
  data () {
    return {
      item: [],
      images: [],
    }
  },
  methods: {
    fetchImages() {
      axios.get(`/api/item/${this.$route.params.id}/${this.$route.params.attribute}/images/`)
      .then(response => {
          this.images = response.data
      })
      .catch(e => {
          this.images = []
          this.errors.push(e)
      })
    },
  },
  computed: {
    main_image() {
      if (typeof this.item[this.$route.params.attribute] !== 'undefined') {
        return this.item[this.$route.params.attribute].image_url
      }
    },
  },
  watch: {
    '$route' (to, from) {
      this.fetchImages()
    }
  },
  created () {
    axios.get(`/api/item/${this.$route.params.id}/`)
      .then(response => {
          this.item = response.data
      })
      .catch(e => {
          this.errors.push(e)
      })
      this.fetchImages();
      self = this
      setInterval(function(){ 
        self.main_image = self.images[Math.floor(Math.random()*self.images.length)].image;
      }, 5000);
  }, 
}
</script>

1 个答案:

答案 0 :(得分:0)

看起来你想要发生以下事情......

  1. main_image最初为null / undefined
  2. 请求/api/item/${this.$route.params.id}/完成后,应为this.item[this.$route.params.attribute].image_url(如果存在)
  3. /api/item/${this.$route.params.id}/${this.$route.params.attribute}/images/的请求完成后,它应该每5秒随机选择一个响应图像。
  4. 我忘了使用计算属性,因为这显然不是你想要的。相反,试试这个

    data() {
      return {
        item: [],
        images: [],
        main_image: '',
        intervalId: null
      }
    },
    methods: {
      fetchImages() {
        return axios.get(...)...
      }
    },
    created () {
      axios.get(`/api/item/${this.$route.params.id}/`).then(res => {
        this.item = res.data
        this.main_image = this.item[this.$route.params.attribute] && this.item[this.$route.params.attribute].image_url
        this.fetchImages().then(() => {
          this.intervalId = setInterval(() => {
            this.main_image = this.images[Math.floor(Math.random()*this.images.length)].image;
          })
        })
      }).catch(...)
    },
    beforeDestroy () {
      clearInterval(this.intervalId) // very important
    }