【问题标题】:$refs.myChildComponent is undefined although I see it in the console$refs.myChildComponent 未定义,尽管我在控制台中看到它
【发布时间】:2019-10-11 14:46:37
【问题描述】:

在我的子组件中,我有两个功能:

methods: {
  tutu: function () {
    ...
  },
  openMenu: function () {
    ...
  }
}

在我的父组件中,我尝试执行每个函数以响应不同的事件:

methods: {
  openMenu: function () {
    this.$refs.main_menu.openMenu();
  },
  handleResize: function () {
    this.$refs.main_menu.tutu();
  }
},

第一次调用 (this.$refs.main_menu.openMenu()) 工作正常,但第二次调用失败并显示以下错误消息:

TypeError: 无法读取未定义的属性“tutu”

在我的父组件中,console.log(this.$refs) 以相同的方式显示这两个函数。编辑:console.log(this.$refs.main_menu) 显示undefined

如果两者都相同,我无法理解为什么其中一个有效,而另一个无效。

main_menu: VueComponent
...
openMenu: ƒ ()
arguments: [Exception: TypeError: 'caller', 'callee', and 'arguments' properties may not be accessed on strict mode functions or the arguments objects for calls to them at Function.invokeGetter (<anonymous>:2:14)]
caller: [Exception: TypeError: 'caller', 'callee', and 'arguments' properties may not be accessed on strict mode functions or the arguments objects for calls to them at Function.invokeGetter (<anonymous>:2:14)]
length: 0
name: "bound openMenu"
...
tutu: ƒ ()
arguments: [Exception: TypeError: 'caller', 'callee', and 'arguments' properties may not be accessed on strict mode functions or the arguments objects for calls to them at Function.invokeGetter (<anonymous>:2:14)]
caller: [Exception: TypeError: 'caller', 'callee', and 'arguments' properties may not be accessed on strict mode functions or the arguments objects for calls to them at Function.invokeGetter (<anonymous>:2:14)]
length: 0
name: "bound tutu"
__proto__: ƒ ()

【问题讨论】:

  • 对象的控制台日志记录是实时的,因此您在展开时看到的是现在对象中的内容,而不一定是记录时的内容。尝试在父组件的函数中记录this.$refs.main_menu。至于为什么,这将取决于打电话给他们的时间。在安装组件之前,refs 不可用。
  • 当我登录this.$refs.main_menu 时,你是对的,我得到undefined。关于时序,这两个函数没有区别,在子组件的methods: {}中依次声明,在父组件的methods: {}中依次声明的函数调用。这是不可理解的……
  • 时间与它们被声明的顺序无关。这是关于他们何时被调用。您没有在问题中包含该代码,因此很难准确,但看起来您在安装之前调用了其中一个,而在安装后调用了另一个。还有其他可能的解释,但我们需要查看调用它们的代码以尝试找出确切的问题。
  • 我专注于声明而不是我从哪里调用它们。有问题的调用是从 created() 钩子发出的,所以当时组件还没有安装,所以你就在现场。如果你愿意,你可以回答我会接受的

标签: vue.js nuxt.js


【解决方案1】:

$refs 只会在组件安装后才会被填充。因此,如果您在此之前尝试访问 ref,例如从 created 挂钩,它将不存在。

ref 可能会以其他方式丢失。例如,如果您使用v-if 并且条件为false。在这种情况下,等待条件变为true 是不够的,您还需要等待执行渲染更新,并且此类更新会排队。在这种情况下,您需要使用 updated 挂钩或调用 $nextTick

【讨论】:

    猜你喜欢
    • 2021-07-13
    • 1970-01-01
    • 2019-10-07
    • 1970-01-01
    • 2017-06-09
    • 2014-10-13
    • 2021-09-13
    • 2021-02-21
    • 1970-01-01
    相关资源
    最近更新 更多