【问题标题】:Computed property "main_image" was assigned to but it has no setter计算属性“main_image”已分配给但它没有设置器
【发布时间】:2018-09-26 22:13:56
【问题描述】:

如何解决此错误“已分配计算属性“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>

【问题讨论】:

  • 你能解释一下你希望什么时候发生吗? main_image 应该在 AJAX 请求完成之前是什么?之后应该是什么,然后每 5 秒应该是什么?
  • @Phil befere AJAX request from fetchImages 它应该是 this.item.main_image 然后每 5s 应该从 fetchImages 迭代 this.images 并将 v-bind:src="main_image" 更改为下一个元素(下一张图片)

标签: vue.js vuejs2


【解决方案1】:

看起来您希望发生以下情况...

  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 秒随机选择一张响应图像。

我会忘记使用计算属性,因为这显然不是您想要的。相反,试试这个

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
}

【讨论】:

    猜你喜欢
    • 2019-05-21
    • 2020-11-07
    • 2020-10-23
    • 2020-10-04
    • 2018-11-02
    • 2019-02-16
    • 2018-02-16
    • 2019-08-01
    • 2020-07-09
    相关资源
    最近更新 更多