programing

VUE 감시가 무한 루프를 트리거했습니다.

itsource 2022. 7. 5. 23:29
반응형

VUE 감시가 무한 루프를 트리거했습니다.

저는 VUE를 처음 써봐요.Js, 그리고 저는 아주 간단한 앱을 만들어서 어떻게 작동하는지 시험해봤어요.

앱 실행 시 무한 루프에서 변수 감시가 트리거되는 즉시 문제가 발생합니다.나는 이유를 알 수 없다.v-for 루프가 있지만 두 개의 요소만 있는 어레이에 있습니다.

처음에 SubTotal은 0이어야 합니다.그러나 앱이 실행되자마자 구매 버튼을 클릭하지 않고 하위 합계가 442.379999999965가 되어 버립니다.

도와주셔서 감사합니다.

여기 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>

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');
  }

});

당신의 실수를 발견했어요.

<button :click="buy(beer)">buy</button>  

사용하셨습니다.:(v-bind대신 )를 사용합니다.@(v-on:를 클릭합니다.

처음 바인드하면 함수가 한 번 호출되어shoppingCart. 이렇게 하면subTotalDOM을 강제로 리렌더하여 DOM을 트리거합니다.buy때문에 다시 기능하다:bind.

수정:

<button @click="buy(beer)">buy</button>  
<!-- or -->
<button v-on:click="buy(beer)">buy</button>  

코드 변경 제안:

메서드 대신 계산된 속성을 사용하여 다른 값의 합계를 나타내는 속성을 업데이트합니다.

new Vue({
  el: "#growler",
  data: {
    beers: [{
        name: 'Ahool Ale',
        price: 2.00
      },
      {
        name: 'Agogwe Ale',
        price: 2.38
      }
    ],
    shoppingCart: []
  },
  watch: {
    shoppingCart: function() {
      console.log('shopping cart watch triggered');
    }
  },
  computed: {
    subTotal: function() {
      return this.shoppingCart.reduce(function(total, beer) {
        return total + beer.price;
      }, 0);
    }
    }
  },
  methods: {
    buy: function(beer) {
      this.shoppingCart.push(beer);
    }
  },

});
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.13/dist/vue.js"></script>
<div id="growler">
  <button>buy</button>
  <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>

언급URL : https://stackoverflow.com/questions/49015152/vue-watch-triggered-infinite-loop

반응형