首页 > 解决方案 > Vue 不渲染数据

问题描述

我有一个复杂的数据结构,而 Vue 处理得很好。然后我对其进行了重构,突然之间似乎没有任何效果。我验证了数据结构已正确组装,但没有显示任何内容。Vue 没有报告任何错误,也没有显示任何内容。

几个小时后,我发现当数据结构包含循环引用时,Vue 渲染系统无法工作。为了验证我定义了两个类 A 和 B。每个都可以引用另一个。

类A.js

export default class classA {
  constructor(name) {
    this.name = name
    this.refB = undefined
  }
  get name() {return this._name}
  set name(n) { this._name= n}
  get type() {return 'classA'}
  get refB() {return this._refB}
  set refB(n) { this._refB= n}
}

类B.js

export default class classB {
  constructor(name) {
    this.name = name
    this.refA = undefined
  }
  get name() {return this._name}
  set name(n) { this._name= n}
  get type() {return 'classB'}
  get refA() {return this._refA}
  set refA(n) { this._refA= n}
}

接下来定义一个显示类 A 列表的 Vue 组件。在挂载生命周期钩子中构造列表,并确保不将类 B 的实例链接回类 A。验证以下呈现 classAList 的每个元素的原始显示

<template lang="pug">
   div Circular References
      div ClassAList length: {{classAlist.length}}
      div(v-for="cA in classAlist")
         div {{cA}}
</template>

<script>
import ClassA from '../classA'
import ClassB from '../classB'
export default {
  data () {
    return {
      classAlist: []
    }
  },
  mounted: function () {
    let a = new ClassA('a1')
    let b = new ClassB('b1')
    a.refB = b
    // Uncomment the next line to create a circular reference in the       
    // data structure. Immediately, once this next line establishes the
    // circular reference the Vue render system fails, silently
    // b.refA = a
    this.classAlist.push(a)
    console.log('Console listing the classA list ', this.classAlist)
  }
}
</script>

检查控制台以查看阵列是否按预期构建。现在取消注释将 B 的实例链接回 A 的实例的代码行。控制台将继续显示数组按预期构造,但 Vue 渲染系统不喜欢循环引用。

有解决方法吗?有没有办法让 Vue 显示一些错误消息。(例如,像 JSON.stringfy 对这样的对象所做的那样)?

标签: vue.jsvuejs2

解决方案


推荐阅读