简体   繁体   English

胡子中的Vue模板语法增量

[英]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. 刚开始学习Vue.js时,我很好奇我的简单代码中发生了什么,我找不到很好的表现。 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. 我在控制台中收到[Vue warn]: You may have an infinite update loop in a component render function. when counter++ is calling. counter++调用时。 I think that I can run expression inside mustache sytaxt but in that case it does not work for me. 我认为我可以在小胡子sytaxt中运行表达式,但在这种情况下它对我不起作用。

Could someone explain what is happening under the hood? 有人能解释一下幕后发生的事情吗?

You are running counter++ , which is counter = counter + 1 , on every render call. 您在每个渲染调用上运行counter++ ,即counter = counter + 1 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. 更改实例状态将重新呈现该组件,这将使计数器一次又一次递增,从而导致无限循环,如Vue会正确警告您。

Instead you should update the counter in your click handler function: 相反,您应该在点击处理程序函数中更新counter

 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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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