【问题标题】:Vue.js - Infinite update loop in a component render functionVue.js - 组件渲染函数中的无限更新循环
【发布时间】:2021-06-28 01:05:41
【问题描述】:

我对我的 vue 代码做了一个小修改,以动态排序我的选择选项:

<option v-for="field in orderByLabels(field.values)" v-bind:value="field.id">
  {{ field.label }}
</option>
methods: {
    orderByLabels: function (dropdown_values) {
      dropdown_values = dropdown_values.sort(function(a, b) {
        return (a.label > b.label) ? 1 : ((b.label > a.label) ? -1 : 0)
      });
      return dropdown_values;
    }
}

这适用于我的界面,但控制台返回以下错误:

[Vue 警告]:组件渲染中可能存在无限更新循环 函数。

好吧,如果有人可以帮助我,我没有使用 Vue.js 的经验。谢谢!!

【问题讨论】:

标签: vue.js


【解决方案1】:

尽量不要使用方法来渲染模板的某些部分。它们在单个渲染周期中执行。见https://vuejs.org/v2/guide/computed.html#Computed-Caching-vs-Methods

改为使用计算属性并避免在 v-for 循环中覆盖您的 field 数据属性

computed: {
  fieldsByLabel () {
    // use spread syntax to make a copy so you don't mutate the source array
    return [...this.field.values].sort((a, b) =>
      a.label.localeCompare(b.label))
  }
}
<option v-for="opt in fieldsByLabel" :value="opt.id">
  {{ opt.label }}
</option>

【讨论】:

    猜你喜欢
    • 2017-10-19
    • 2020-04-30
    • 2020-06-03
    • 2018-11-29
    • 1970-01-01
    • 2021-01-12
    • 2019-12-28
    • 2019-02-07
    • 2017-08-26
    相关资源
    最近更新 更多