vuejs - 为什么这是无限循环?

时间:2018-01-30 18:25:50

标签: javascript vue.js

我有这个“基本”函数,它检查数组中的[i]元素是否与id相同:

    checkArray(offer, id){
        if (id)
        {
            this.count=0;
            for (var i in offer.specialities) {
                if (offer.specialities[i] == id)
                {
                  console.log("bam!")
                  // this.count=+1;
                  return true;
                  break;
                } 
            }
            return false;
        }
        else {
            return true;
        }
    },

变量计数在vuejs数据中声明

data() {
  return {
    count: 0 
  } 
}

从v-show调用checkArray:

<v-layout  row wrap v-for="offer in offers.slice((current_page-1)*5, current_page*5)" 
v-show="checkArray(offer, speciality)">

此时一切运作良好。我有两个光头。

现在我取消注释this.count=+1; 我有200个bams!和我的vuejs控制台尖叫:

[Vue warn]: You may have an infinite update loop in a component render function.

为什么会这样?如何计算变量中的凸轮数?

1 个答案:

答案 0 :(得分:1)

Vue认为你有一个无限循环,因为你在同一个循环中读取并修改了count变量。

因为您在循环中读取变量count,所以vue将开始监视任何更新的count变量。

因为您编写了count变量,所以vue将在下一个tick中重新运行每个侦听器。

您应该将循环体的计算委托给单独的计算属性。

currentPageView() {
    return this.offers.slice((current_page-1)*5, current_page*5);
},

shownPageView() {
    const result = [];
    for(let i = 0; i < currentPageView.length; i++) {
        const offer = currentPageView[i];
        const id = this.speciality;
        if (id) {
            this.count=0;
            for (var i in offer.specialities) {
                if (offer.specialities[i] == id) {
                  result.push(offer);
                  break;
                } 
            }
        } else {
             result.push(offer);
        }
    }
    return result;
},

countSpecialOffers() {
    let count = 0;
    for(let i = 0; i < currentPageView.length; i++) {
        const offer = currentPageView[i];
        const id = this.speciality;
        if (id) {
            this.count=0;
            for (var i in offer.specialities) {
                if (offer.specialities[i] == id) {
                  count++;
                  break;
                } 
            }
        }
    }
    return count;
}

执行此操作后,您可以同时访问shownPageView以循环搜索结果,并countSpecialOffers获取特别优惠的计数

相关问题