0

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?

0

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks, i had to put the watcher outside of the computed function but it works great.
Yeah sorry, it was my mistake. It should be outside indeed. Glad it helps! I updated the answer btw.
Still wondering why the example on the doc doesn't work vuejs.org/v2/guide/computed.html#Computed-Setter
You can take a look at a small example I just wrote here: jsfiddle.net/k7zw3na5/6.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.