【问题标题】:Component instance is undefined组件实例未定义
【发布时间】:2019-04-24 15:14:42
【问题描述】:

我像这样创建 Vue/Vuetify 组件:

let item = this.$createElement(ComponentName, {
   props: {
       displayField: this.displayField,
       valueField: this.valueField,
       childrenField: this.childrenField,
       level: this.level + 1,
       checkboxes: this.checkboxes,
       items: child,
       parentNode: this,
       root: this.root
    }
});

我需要的是获取项目的componentInstance 属性。如果我这样做:

console.log(item.componentInstance);
console.log(item);

我看到item.componentInstanceundefined。但是,当我在控制台中调查item 时,我看到它有这个componentInstance 属性,而不是undefined。下面是这两条命令的截图:

那么,这有什么问题呢?如何以编程方式访问此componentInstance

【问题讨论】:

  • 试试setTimeout(() => console.log(item.componentInstance), 150) 还是不确定吗?
  • @Dani R. 我查过了。它是未定义的。但我不想这样。它看起来像一个肮脏的黑客。
  • 确实如此,我不会推荐它。但是创建实例需要时间。

标签: javascript vue.js vuetify.js


【解决方案1】:

当您编写console.log(object) 时,浏览器会在内存中记录对该对象的引用。因此,当您尝试在运行时检查它时,您将看到对象处于其当前状态,而不是处于执行 console.log 时的状态。

所以这里发生的情况是,当您在组件创建时显式访问 item.componentInstance 时,它尚未定义。如果您当时可以查看项目的快照(例如console.log(JSON.stringify(item))),您可以确认componentInstance 确实未定义(实际上,stringify 在这里不起作用,因为 Vue 在其内部结构中使用循环引用,而你不能stringify这样的对象)

但是当您执行console.log(item) 时,您会将对该对象的引用记录在内存中。因此,当它显示在您的控制台中并单击它时,该组件已经安装并呈现,并且自您要求记录它的那一刻起,它的属性已更改

如果您的处理很简单并且只进行一次,将其移至mounted() 应该可以解决问题。

如果您有更复杂的处理,其中元素会在运行中重新渲染(例如您的新动态组件),您需要等待它们实际渲染,然后才能访问它们的 componentInstance。所以,你应该用Vue.nextTick(如果使用SFC,this.$nextTick)包装访问渲染元素(例如componentInstance)的代码

【讨论】:

    【解决方案2】:

    你得到 undefined 因为组件的 DOM 尚未更新。所以你必须借助 vue nextTcik 函数。

    你可以试试这个解决方案:

    let item = this.$createElement(ComponentName, {
       props: {
           displayField: this.displayField,
           valueField: this.valueField,
           childrenField: this.childrenField,
           level: this.level + 1,
           checkboxes: this.checkboxes,
           items: child,
           parentNode: this,
           root: this.root
        }
    });
    this.nextTick(() => {
          console.log(item.componentInstance);
          console.log(item);
          }); 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-03-18
      • 2020-02-16
      • 1970-01-01
      • 2020-12-11
      • 1970-01-01
      • 1970-01-01
      • 2018-08-13
      • 1970-01-01
      相关资源
      最近更新 更多