1

I am new in Vuejs & still not pretty clear about vue reactivity system. Here in the following code I am trying to update the initial value of a variable in data property using a method.

<script>
  name: "OrderDetails",
  data(){
    tax:5,
    subtotal:0
  },

  computed:{
    calculateSubtotal:()=> {
      let subtotal;

      -----some code--------

      this.subtotal = subtotal;
    }
  }
</script>

But still the subtotal remains 0. How can I Update the value ? Here is the code snippet https://codesandbox.io/s/affectionate-borg-384rl?file=/src/App.vue

Thanks in advace.

3
  • Do you call/run/output that computed property anywhere? (Also, I think you should use a watcher instead or just return subtotal from your method) vuejs.org/v2/guide/computed.html Commented Apr 16, 2020 at 8:18
  • 1
    My advice - if you are a newbie - follow the VUE docs (Great docs). For example you wont find any arrow function under the computed docs calculateSubtotal:()=> { vuejs.org/v2/guide/computed.html Commented Apr 16, 2020 at 8:59
  • Vue.js docs are great, but the information regarding fat arrow/function is not straight forward. I can see how a beginner could easily miss this. Commented Apr 16, 2020 at 9:13

1 Answer 1

5

There are a few errors in your code

  1. You must not use fat arrow when declaring computed methods. this will not bind to your instance.
computed:{
  calculateSubtotal() {
      let subtotal;

      -----some code--------

   this.subtotal = subtotal;
  }
}
  1. Your computed methods should not have side effects. This means that you must compute values based on data or external information, but do not update data from within the method. You should return the value you want.
computed:{
  calculateSubtotal() {
    let subtotal;

      -----some code--------

    return subtotal;
  }
}
  1. If you never reference the computed method (call it) it will not execute. You're not calling calculateSubtotal anywhere and as such it is never run. You need to call it somewhere. In the template for instance.
{{{calculateSubtotal}}

Here's an example with proper this, returning a value and calling the computed method. But you shouldn't do this. This bring me to no 4.

  1. You should just use the computed method as any other data, and not pass it as params to other methods. This will work in methods also.

This is a complete example

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.