Vue js increment operator(++) not giving expected output

Viewed 286

Why the below vue js code showing output 102.

<html>
<head>
   <script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
</head>
<body>
   <div id = "intro" style = "text-align:center;">
      <h1>{{ ++serial }}</h1>
   </div>
   <script type = "text/javascript">
      var app = new Vue({
         el: '#intro',
         data: {
            serial: 0
         }
      });
   </script>
</body>
</html>

I need an explanation. My expected output is 1. How to fix that?

2 Answers

It's not allowed to run statements that update component's properties inside the template because this will make an infinite loop, you could achieve the desired behavior using a computed property as shown below:

var app = new Vue({
  el: '#intro',
  data: {
    serial: 0
  },
  computed: {
    incrementedSerial() {
      return ++this.serial
    }
  }
});
<script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>

<div id="intro" style="text-align:center;">
  <h1>{{ incrementedSerial }}</h1>
</div>

That's an assignment statement, which isn't allowed in an interpolation.

From the docs:

These expressions will be evaluated as JavaScript in the data scope of the owner Vue instance. One restriction is that each binding can only contain one single expression, so the following will NOT work:

<!-- this is a statement, not an expression: -->
{{ var a = 1 }}

Your code is roughly the equivalent of:

{{ serial = serial + 1 }}

Here's how you could make a calculation with it in a loop:

new Vue({
  el: "#app",
  data() {
    return {
      serial: 0
    }
  }
});
<div id="app">
  <div v-for="i in 5">
    {{ i + serial }}
  </div>
</div>

<script src="https://unpkg.com/vue/dist/vue.min.js"></script>

Related