I need to save the computed value in my database, but it seems i cannot access it with the following example :
computed: {
total: {
get: function() {
return this.items.reduce(
(acc, item) => acc + (item.price * item.quantity) * (1 - item.discount/100), 0
)
},
set: function(newValue) {
console.log(newValue);
// this.tototata = newValue;
}
}
},
In the template, the computed value working well, but nothing appears in the console
I'm working with vue 2.6.11
Is this the best way to do this? Should i use methods?
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.