WoJ WoJ - 1 month ago 5
Javascript Question

Can a variable in data be computed based on other data?

I would like to have some of the

data
variables computed based on some other variables and follow their changes in the
Vue
instance. The natural solution



new Vue({
el: '#root',
data: {
a: 1,
b: a + 1
}
})

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.0.3/vue.js"></script>

<div id="root">
{{ a }} and {{ b }}
</div>





fails with
Uncaught ReferenceError: a is not defined
.

Is it possible to use previously defined variables to create new ones on the fly?

WoJ WoJ
Answer

The solution is to use computed values, b will be accessible the same way as if it was declared in data:

new Vue({
  el: '#root',
  data: {
    a: 1
  },
  computed: {
    // a computed getter
    b: function() {
      // `this` points to the vm instance
      return this.a + 1
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.0.3/vue.js"></script>

<div id="root">
  {{ a }} and {{ b }}
</div>