VUE手表触发无限循环

use*_*137 4 javascript vuejs2

我是 VUE.Js 的新手,我创建了一个非常简单的应用程序来尝试它是如何工作的。

问题立即发生,当我运行应用程序时,在无限循环中触发变量监视。我不明白为什么。有一个 v-for 循环,但它位于一个只有两个元素的数组上。

最初 SubTotal 应该是 0。但是一旦应用程序运行,它就会触发 Buy 方法,即使我没有点击购买按钮,并且 subtotal 最终是 442.37999999999965。

谢谢你的帮助。

这是 jsfiddle啤酒购物车

HTML :

<div id = "growler">      
  <table>
    <tr>
      <th style='width:150px'>Beer</th>
      <th style='width:50px'>Price</th>
      <th style='width:30px'></th>
    </tr>

    <tr v-for = "beer in beers">
      <td>{{ beer.name }}</td>
      <td>{{ beer.price }}</td>
      <td>        
        <button :click="buy(beer)">buy</button>        
      </td>
    </tr>

    <tr>
      <td>SubTotal</td>
      <td>{{subTotal}}</td>
      <td></td>
    </tr>
  </table>
</div>
Run Code Online (Sandbox Code Playgroud)

JS:

  new Vue({
  el: "#growler",
  data: {
      beers: [
        {name: 'Ahool Ale', price: 2.00}, 
        {name: 'Agogwe Ale', price: 2.38}        
      ],
      shoppingCart: [], 
      subTotal: 0.00        
  }, 
  watch: {
    shoppingCart: function() {
        console.log('shopping cart watch triggered');
      this.updateSubTotal();
    }
  }, 
  methods: {
    updateSubTotal: function () {
      var s=this.shoppingCart.length;
      var t=0;
      for (var i=0;i<s; i++){
        t += this.shoppingCart[i].price;
      }
      this.subTotal = t;
    }, 
    buy: function (beer) {
        console.log('beer pushed on array');
      this.shoppingCart.push(beer);
    }
  },   
  beforeCreate: function() {
    console.log('beforeCreate');
  },
  created: function() {
    console.log('created');                    
  },
  beforeMount: function() {
    console.log('beforeMount');                    
  },
  mounted: function() {
    console.log('mounted');                    
  },
  beforeUpdate: function() {
    console.log('beforeUpdate');
  },
  updated: function() {
    console.log('updated');
  },
  beforeDestroy: function() {
    console.log('beforeDestroy');
  },
  destroyed: function() {
    console.log('afterDestroy');
  }

});
Run Code Online (Sandbox Code Playgroud)

Phi*_*ter 7

我发现你的错误:

<button :click="buy(beer)">buy</button>  
Run Code Online (Sandbox Code Playgroud)

您在点击处理程序上使用:( v-bind) 而不是@( v-on:) 。

当您第一次绑定它时,该函数会被调用一次并更新shoppingCart. 这将更新subTotal数据,这将强制重新渲染 DOM,buy由于:bind.

使固定:

<button @click="buy(beer)">buy</button>  
<!-- or -->
<button v-on:click="buy(beer)">buy</button>  
Run Code Online (Sandbox Code Playgroud)

对您的代码的建议更改:

使用计算属性而不是方法来更新表示其他值总和的属性:

<button :click="buy(beer)">buy</button>  
Run Code Online (Sandbox Code Playgroud)
<button @click="buy(beer)">buy</button>  
<!-- or -->
<button v-on:click="buy(beer)">buy</button>  
Run Code Online (Sandbox Code Playgroud)