0

我在动态添加到组件列表时遇到问题。

我已经在 vue 文档的数据元素“事物”中定义了列表。对于“事物”中的每个对象,页面上都会加载一个组件

  data() {
    return {
      things: []
    }
  }

我使用类似下面的代码来加载页面上的每个内容。

  <div v-for="thing in things" :key="thing.objectId">

然后我加载更多元素并将它们添加到列表中

        let temp = JSON.parse(JSON.stringify(results))
        vm.things = vm.things.concat(temp) 

当我在 dev 中运行它时,我得到以下信息

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

除了错误消息之外,代码在开发模式下工作,但在生产中运行时会导致浏览器崩溃。

我已经把它缩小到这段代码,循环中有一点打印出一个标题,它是数据所属的月份,所以它可能会说一月,然后列出一月下的所有数据,然后到下个月等等

showDate(data) {
  this.currentDataMonth = helperfunctionsgetDate_format_month_year(data)
  if (this.currentDataMonth != this.currentmonth) {
    this.currentmonth = this.currentDataMonth
    return "<h2>" + this.currentmonth + "</h2>"
  } else {
    return ""
  }
4

1 回答 1

0

您的问题是由于您都修改状态并使用相同方法的状态引起的。

showDate(data) {
  this.currentDataMonth = helperfunctionsgetDate_format_month_year(data) // set of the state
  if (this.currentDataMonth != this.currentmonth) { // get of the state
    this.currentmonth = this.currentDataMonth
    return "<h2>" + this.currentmonth + "</h2>"
  } else {
    return ""
  }

由于您直接在函数中使用这些变量,因此将它们设为函数的本地变量

showDate(data) {
  const currentDataMonth = helperfunctionsgetDate_format_month_year(data)
  if (currentDataMonth != undefined) {
    const currentmonth = currentDataMonth
    return "<h2>" + currentmonth + "</h2>"
  } else {
    return ""
  }

由于代码的目的是在其自己的标题下列出每个月,因此您应该使用计算函数来返回每个月的数据列表,并使用 2 个循环来循环

于 2018-07-09T10:50:21.793 回答