Home > Software engineering >  Which data properties need to change to trigger an update?
Which data properties need to change to trigger an update?

Time:04-23

I am practicing vue js. This is the vue.js code

new Vue({
 el: '#people',
 data: {
  var1: 0,
  var2: null,
  var3: 'Hello',
  var4: 'Yassss'
 },
 computed: {
  var5: function() {
  let var1 = 0;
  if(this.var2 != null){
    var1  ;
  }
  console.log(this.var3);
  return var1;
 }
}
});

This is the html code

<p>{{ var5 }}</p>

The thing I am trying to understand is which data properties would need to change to trigger an update to the page

Currently it is giving out the following output:

{{ var5 }}

I tried changing all of them in different combinations but it doesn't seem to work.

CodePudding user response:

data property must be a function:

data() {
  return  {
    var1: 0,
    var2: null,
    var3: 'Hello',
    var4: 'Yassss'
  }
},

new Vue({
  el: '#people',
  data() {
    return {
      var1: 0,
      var2: null,
      var3: 'Hello',
      var4: 'Yassss'
    }
  },
  computed: {
    var5() {
      let var1 = 0;
      if(this.var2 != null){
        var1  ;
      }
      console.log(this.var3);
      return var1;
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="people">
  <p>{{ var5 }}</p>
</div>

CodePudding user response:

A computed is used mainly to trigger changes regarding what it's returning, hence if you return var1, you should mutate it somewhere in your code (v-model, this.var1 = ... etc).

Keep in mind that using a conditional like this.var2 != null doesn't have a lot of meaning because the computed() will not be "called" until var1 is updated.
I recommend reading enter image description here

  • Related