[Vuejs]-Vuejs computed, make it reactive

1πŸ‘

βœ…

I think the computed setter is called when manually setting the computed value. For example, the setter will be triggered if you do something like this.total = newTotal. In order to save the computed value in the database whenever it’s updated, you might want to set up a watcher:

computed: {
  total: {
    get: function() {
      return this.items.reduce(
        (acc, item) => acc + (item.price * item.quantity) * (1 - item.discount / 100), 0
      )
    }
  }
},
watch: {
  total(newValue) {
    // Save to database
  }
}

You can read more about Computed Setter here. Hope that this can help you solve the problem.

πŸ‘€Andrew Bui

Leave a comment