0

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
  • 27,165
  • 48
  • 180
  • 345
  • Possible duplicate of [Self-references in object literal declarations](http://stackoverflow.com/questions/4616202/self-references-in-object-literal-declarations) – JJJ Nov 02 '16 at 13:40
  • `data: { a: 1, b: a + 1 }` a is an var in data? – Kevin Kloet Nov 02 '16 at 13:41
  • @JJJ: wouldn't the `init` part in the linked answer be calculated only once? I would like `b` to follow the changes of `a`. – WoJ Nov 02 '16 at 13:42
  • That you can't do. `b` would have to be a function, or you'd need to set a [getter](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/get) for `b` but I don't know if Vue supports that. – JJJ Nov 02 '16 at 13:44
  • obj = new Vue(//stuff//) then access it by obj.data.a and obj.data.b – Jackstine Nov 02 '16 at 13:45
  • (Or maybe Vue provides another way to do it, I'm not familiar with it.) – JJJ Nov 02 '16 at 13:45
  • @JJJ: I just found the right approach for Vue (and posted as an answer). Thanks for the hints (and the answer is not a duplicate but I am not sure about how to advertise that) – WoJ Nov 02 '16 at 13:53

2 Answers2

3

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>
WoJ
  • 27,165
  • 48
  • 180
  • 345
-1

try this

var x;
new Vue(x = {
   el: '#root',
   data: {
     a: 1,
     b: () =>  x.data.a + 1
   }
})
Semi-Friends
  • 480
  • 5
  • 17