【问题标题】:vuejs - why this is infinite loop?vuejs - 为什么这是无限循环?
【发布时间】:2018-01-30 18:25:49
【问题描述】:

我有这个“基本”函数,它检查数组中的 [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 
  } 
}

checkArray 是从 v-show 调用的:

<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.

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

【问题讨论】:

  • 这不是无限循环,而是语法错误。您不能拥有for (i=0 in offer.specialities)。您可以使用for (i in offer.specialities),但不能使用=0
  • i=0 in offer.specialities 那该怎么办??
  • @JonasW.:如果是的话,它需要两个;s。
  • 也许无限循环是调用checkArray的地方
  • @gileneusz 你在哪里打电话给checkArray? ...您能提供您的代码中的template 吗?最有可能发生的是,在您的 checkArray 方法中使用 this.count 会一遍又一遍地改变状态,导致组件每次都重新渲染。

标签: javascript vue.js


【解决方案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 以获取特别优惠的数量

【讨论】:

  • 这是答案,我不知道为什么会这样
猜你喜欢
  • 2011-11-15
  • 2021-08-16
  • 2018-01-13
  • 2020-08-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多