Search code examples
vue.jscomputed-properties

Vue.js and Computed Properties


Here is my code:

  <div id="app">
  <p>here is the message: {{message}}</p>
  <p>{{a}}</p>
  <p>here is the reversed message: {{reversedMessage}}</p>

</div>
<script type="text/javascript">
  var vm = new Vue({
    el: '#app',
    data: {
      message: 'Hello',
      a: 1,
    },
    computed: {
      reversedMessage: function () {
        this.a += 1;
         return this.message.split('').reverse().join('')
      }
    }
  });
</script>

First of all, why the value for a becomes 2? I thought since a is before the computed property, it's value should be 1 and then in the next line and after calling the function for computed property, it's value would be 2. Could you please explain this to me?

and second: in the chrome DevTools, when I change the value for a (like below):

vm.a = 8

in the p tag, the value for a becomes a+1. Why?! So every time I change the value for a in the DevTools Console, the value for a in p tag become a+1! why the function for computed property is called and changes the value for a?


Solution

  • Because a is defined in your data, it becomes a reactive property. That means anytime you change it, the change will be reflected everywhere. That's why a == 2 initially in your text, because you change it in your computed value.

    Secondly, if you change a in the devtools console, the reversedMessage will be recalculated because you reference a inside it. So the sequence is

    1. Change a in devtools.
    2. reversedMessage is triggered, because a is referenced inside it.
    3. a now equals a + 1
    4. Vue updates the DOM referencing a, <p>{{a}}</p>

    In summary, a is going to display it's current value everywhere you display it, and changing a via the console, causes a to be incremented.