[Vuejs]-Computed property "main_image" was assigned to but it has no setter

0👍

Looks like you want the following to happen…

  1. main_image is initially null / undefined
  2. After the request to /api/item/${this.$route.params.id}/ completes, it should be this.item[this.$route.params.attribute].image_url (if it exists)
  3. After the request to /api/item/${this.$route.params.id}/${this.$route.params.attribute}/images/ completes, it should randomly pick one of the response images every 5 seconds.

I’d forget about using a computed property as that is clearly not what you want. Instead, try this

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
}

0👍

You have to add setter and getter for your computed proterty.

 computed: {
    main_image: {
      get() {
         return typeof this.item[this.$route.params.attribute] !== 'undefined' && this.item[this.$route.params.attribute].image_url
      },
     set(newValue) {
       return newValue;
     },
   },
},

Leave a comment