Search code examples
objectvuejs2calccomputed-properties

Simple addition in vue data


I want to add two numbers in vue

data() {
  return {
    details: {
        num1: 100,
        num2: 500,
        total: num1 + num2
}
  }
    }

Is this not possible and bad practice? I can create a computed but this as a temp shortcut would be useful. Is it just the scope I have wrong?


Solution

  • It's a very bad practice! In Vue.js you should always use computed properties for any calculation.

    But in your case you should do something like this:

    <template>
      <div>{{details.total()}}</div>
    </template>
    
    <script>
    
    export default {
    
      data() {
        return {
          details: {
              num1: 100,
              num2: 500,
              total: () => this.details.num1 + this.details.num2
            }
          }
        }
      }
    
    }
    </script>