【问题标题】:vue error: infinite update loop in a component render functionvue 错误:组件渲染函数中的无限更新循环
【发布时间】:2018-11-29 14:09:50
【问题描述】:

我正在制作一个包含随机创建的数字的表格,但是当我在 v-for 中调用 contacts() 时,出于某种原因, 我收到了这个红色警告:

vue.esm.js?efeb:591 [Vue 警告]:您可能在组件渲染函数中有无限更新循环。在 src\App.vue 的---> 中找到

有一堆空数组,比如“[]...”

为什么会这样以及如何解决?

<template>
   <div id="app">
    <table border=1 width =50% id="list">
        <tr v-for="i in [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1]">
          <td v-for="contact in contacts()">{{contact}}</td>
      </tr>
    </table>
  </div>
</template>

<script>
  import Vue from 'vue'

  export default {
    name: "App",
    data: function() {
      return {
        result: [],
        row: Math.floor(Math.random() * 16) + 1
      }
    },
    created() {
      let start = Math.floor(Math.random() * 16) + 1
      for (var i = 0; i < 16; i++) {
        this.result[i] = start++
        if (start > 16) start = 1
      }
    },
    methods: {
      contacts: function() {
        let snapshot = this.result.splice(0, this.row)
        console.log(snapshot)
        return snapshot
      }
    }
  }
</script>

【问题讨论】:

    标签: vue.js


    【解决方案1】:

    contacts 方法在渲染期间被调用,其中 this.result.splice() 修改了 this.result,Vue 将检测并安排组件的重新渲染。在渲染期间改变反应组件状态是导致此警告的原因。

    因为你实际上并没有使用i,而不是

    <tr v-for="i in [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1]">
    

    你可以的

    <tr v-for="i in 17">
    

    我不太确定您要达到的目标。看起来您想渲染一个有 17 行的表格,每行包含从 1-16 之间的随机整数开始的连续整数,并且数字环绕?

    【讨论】:

    • 表格具有随机宽度(1~16)和随机高度(1~16),并且仍然相同。
    猜你喜欢
    • 2020-04-30
    • 2017-10-19
    • 2021-04-30
    • 2021-06-28
    • 1970-01-01
    • 2019-02-12
    • 2018-05-03
    • 1970-01-01
    • 2021-05-05
    相关资源
    最近更新 更多