[Vuejs]-Vue.js computed beginner

0👍

Some problems.

First, you have syntactical problems. data is an object, so instead of:

data:{
  show = true;
}

Should be:

data:{
  show: true
}

Next, computed properties are to be used like… properties. For example, like declared in data. So, typicall, you read from them. You don’t execute computed properties in @click events. So this code:

<button @click="showToggle1">Switch!</button>

Is not correct. It will error because showToggle1 is not a method, it is, as said, a computed property. What you should have in click is a method, like:

<button @click="showToggle2">Switch!</button>

This will work because showToggle2 is a method. And you should use methods to perform changes.

Not, before going into the last and most tricky part, here’s a working demo:

new Vue({
  el: '#app',
  data: {
    show: true
  },
  computed: {
    /*showToggle1: function() {
      return this.show = !this.show;
    }*/
  },
  methods: {
    showToggle2: function() {
      this.show = !this.show;
    }
  }
});
<script src="https://unpkg.com/vue"></script>


<div id='app'>
  <p>Do you see me?</p>
  <p v-if="show">Do you also see me?</p>
  <hr>
  Value of show: {{ show }}<br>
  <button @click="showToggle2">Switch2!</button>
</div>

The tricky part is your computed property (which I commented out in the code above):

  computed:{
     showToggle1:function(){
     return this.show = !this.show
     }
  },

Basically what it is doing is it is automatically negating the value of show whenever it changes.

This happens because the computed property is calculated whenever show updates. And what is happening is:

  • You initialize data with true (because of data: {show: true}).
  • The showToggle1 computed auto-recalculates, because it has this.show inside of it (it depends on it).
  • When recalculating, showToggle1 sets the value of show to false (because of return this.show = !this.show).

That’s why show becomes false.

And that’s also why whenever you change (even from the method, which is the correct place) the value of show to true it will automatically go back to false. Because any change in show triggers the showToggle1 computed recalculation, which sets show back to false.

In summary:

  • Use methods to perform changes.
  • Don’t change properties inside computed properties.

Leave a comment