您可能在组件渲染函数中有无限更新循环

新手上路,请多包涵

我是 VueJS 的新手,我收到了来自 Vue 的警告,

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

当我在 V-bind:style 中使用 V-for 变量时,这是一个示例:在模板中:

 <div v-for="item in model.items" v-bind:class="test(item.result)">
{{item.id}}
</div>

在脚本中:

 data() {
    return {
        accept: false,
        not_accept: false,
    };
},
methods: {
    test(result) {
        if (result == 'accept') {
            this.accept = true;
            this.not_accept = false;
        } else if (result == 'Not accept') {
            this.accept = false;
            this.not_accept = true;
        } else {
            console.log(result);
        }

        return {
            success: this.accept,
            danger: this.not_accept,
        };
    },
},

原文由 ramzi trabelsi 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.6k
2 个回答

@Decade 对这个问题是正确的。这是确切的问题:

  1. 您正在使用某些状态值呈现项目列表的渲染方法

注意:每当任何状态发生变化时都会触发渲染方法

  1. 然后,您尝试根据函数 test 的结果绑定类,该函数有缺陷,因为它再次尝试改变状态,从而导致渲染 - 测试 - 渲染循环。

您可以通过使您的测试函数不改变状态来解决此问题,如下所示:

 methods: {
    test(result) {
        let accept;
        if (result == 'accept') {
            accept = true;
        } else if (result == 'Not accept') {
            accept = false;
        } else {
            console.log(result);
        }

        return {
            success: accept,
            danger: !accept,
        };
    },
}

我希望这有帮助!

原文由 aks 发布,翻译遵循 CC BY-SA 3.0 许可协议

我不小心做了类似的事情,用未经训练的眼睛不容易发现:在过滤器中的数组上调用 .sort()sort 改变数组,从而使组件重新渲染。解决方法是先将 slice 数组创建一个浅拷贝,然后排序。

坏的:

  filters: {
    sortedDays(days) {
      return days.sort().join(', ');
    },
  },

好的:

  filters: {
    sortedDays(days) {
      return days.slice().sort().join(', ');
    },
  },

原文由 Andy 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题