简体   繁体   中英

Vue template syntax increment in mustache

Just started learn Vue.js and I am very curious what happened in my simple code, I cannot find explenation. I am trying to increment counter inside mustache, but there is something weird happening with this variable

my code:

 new Vue({ el: '#app', data: { counter: 5, state: false }, methods: { fun: function() { this.state = !this.state } } }) 
 <script src="https://unpkg.com/vue"></script> <div id="app"> <p>{{ counter }}</p> <button v-on:click="fun">Button</button> <p v-if="state"> Miss me? {{ counter++ }} </p> </div> 

I am receiving in console [Vue warn]: You may have an infinite update loop in a component render function. when counter++ is calling. I think that I can run expression inside mustache sytaxt but in that case it does not work for me.

Could someone explain what is happening under the hood?

You are running counter++ , which is counter = counter + 1 , on every render call. Changing your instance state will re-render the component, which will increment the counter again and again, leading to an infinite loop like Vue correctly warns you.

Instead you should update the counter in your click handler function:

 new Vue({ el: '#app', data: { counter: 5, state: false }, methods: { fun: function() { this.counter++; this.state = !this.state } } }) 
 <script src="https://unpkg.com/vue"></script> <div id="app"> <p>{{ counter }}</p> <button v-on:click="fun">Button</button> <p v-if="state"> Miss me? {{ counter }} </p> </div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM