【发布时间】: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()钩子发出的,所以当时组件还没有安装,所以你就在现场。如果你愿意,你可以回答我会接受的