Search code examples
vue.jsincrement

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


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?


Solution

  • 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>