1

I have a computed property function called: Total, this essentially calculates the name + value pairs of an array called prices, it's for a quotation form whereby a running total is added up as a user progresses through a multi-step form, values are then pushed into an array to keep things clean.

This computed property allows me to echo the total on the page which is dynamically updated without any additional code, I can simply add total using handlebars to wherever I want on my page like so: {{ total }}

The problem I'm now facing is that I also want the value of 'total' to be included in a separate array, or at least added to an array and I can't seem to get it right.

The working code which gets the values of my prices array which is by default empty is as follows:

computed: {
    total: function(){
      var total = [];
      Object.entries(this.prices).forEach(([name, value]) => {
        total.push(value)
      });
      return total.reduce(function(total, num){
        return total + num
      }, 0);
    }
  }

I want to do add something like this to my computed property:

this.quote.totalPrice = total

I've tried:

computed: {
    total: function(){
      var total = [];
      Object.entries(this.prices).forEach(([name, value]) => {
        total.push(value)
      });
      return total.reduce(function(total, num){
        return total + num
        this.quote.totalPrice = total 
      }, 0);
    }
  }

I'm not getting anything with this?

2
  • 4
    this.quote.totalPrice = total is after a return and unreachable, but you can't do this anyway. Computed properties are standalone and not meant to alter state. Why do you need to this? Either expand your computed property to include the rest of this.quote, or just fetch total when you need to construct your quote object Commented Feb 10, 2019 at 16:23
  • 4
    Like jpriebe said its not advisable to mutate data in computed. you can add a watcher for total and then assign total to quote.totalPrice inside that Commented Feb 10, 2019 at 17:00

1 Answer 1

1

You can use a watcher to keep track of changes to your computed property and update any variables accordingly:

watch: {
  total(newTotal) {
    this.quote.totalPrice = newTotal
  }
}
Sign up to request clarification or add additional context in comments.

Comments

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.