0

I tried to implement a simple sample using element-ui. There are two 'switches' () each one has the value for active state: 2 and 1. The switches' values are displayed in <p>{{sw1}}</p> and <p>{{sw2}}<>/p> like this.

The image of sample app

Here is the component source 'Sample.vue':

<template>
  <div class="wrapper">
    <el-switch v-model="sw1" active-value=2 inactive-value=0></el-switch>
    <p>{{sw1}}</p>
    <el-switch v-model="sw2" active-value=1 inactive-value=0></el-switch>
    <p>{{sw2}}</p>
    <p>{{value}}</p>
  </div>
</template>

<script>
export default {
  data () {
    return {
      sw1: 0,
      sw2: 0
    }
  },
  computed: {
    value: () => {
      return Number(this.sw1) + Number(this.sw2)
    }
  }
}
</script>

It was supposed that <p>{{value}}</p> shows the computed ( sw1 + sw2 ) value, however it always shows NaN in spite of <p>{{sw1}}</p> and <p>{{sw2}}<>/p> were changed correctly when the status of switches are changed.

Why does computed: always return NaN?

HirofumiTamori
  • 1,125
  • 2
  • 13
  • 27

1 Answers1

3

You shouldn't use arrow function. Please, do a test and check what is this in your code.

Check this

computed: {
  value: function () {
    return Number(this.sw1) + Number(this.sw2)
  }
}

Vue binding application instance to this function under the hood. It isn't possible for arrow functions.

ventaquil
  • 2,780
  • 3
  • 23
  • 48