【问题标题】:Why is Vue warning me about infinite loop?为什么 Vue 会警告我关于无限循环?
【发布时间】:2021-11-09 20:25:02
【问题描述】:

Vue 警告我以下消息:

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

我发现我应该使用计算而不是方法,但它对我不起作用。是什么导致了这个问题?一切正常,没有发生无限循环,但 Vue 仍在警告我。

.battle__invite(v-for='(invite, index) in invites', :key='index')
  battle__result.battle__result--finished(         
      :class='getResultClass(invite.challengerScore, invite.challengedScore)'
    ) {{ challengeResult }}

计算:

getResultClass() {
      return (challengerScore, challengedScore) => {
        if (challengerScore > challengedScore) {
          this.challengeResult = 'win'
          return 'win'
        } else if (challengerScore < challengedScore) {
          this.challengeResult = 'defeat'
          return 'defeat'
        } else {
          this.challengeResult = 'draw'
          return 'draw'
        }
      }
    },

【问题讨论】:

    标签: javascript vue.js


    【解决方案1】:

    这是因为challengeResult 变量。您在模板和计算属性中都使用它,这会导致无限重新渲染。

    如果你写一个console.log("im in computed property") 并把它放在getResultClass 中,你会得到大约200 个console.log,这显示了无限重新渲染错误。但是 vue 不允许进行无限重新渲染并停止它(多么棒的框架!)

    原因很简单!在模板中使用getResultClass。在此计算中,您更改 challengeResult 变量。然后因为您在模板部分使用challengeResult,它会导致另一个重新渲染并且计算属性再次运行。而且这个循环永远存在!

    【讨论】: