我正在尝试从子组件中定义的父组件访问引用。我有一个文件,我在其中调用父组件,在组件内部我调用 2 个子组件,如下所示:
<my-component>
<component-header></component-header>
<component-content></component-content>
</my-component>
Run Code Online (Sandbox Code Playgroud)
里面my-component我有一个<slot></slot>,没有其他 html,但这就是我需要调用 .txt 文件中列出的 ref 的地方component-header。这是我的component-header文件:
<template>
<div ref="mycomponentHeader">
<slot>
// Here some other html
</slot>
</div>
</template>
Run Code Online (Sandbox Code Playgroud)
我如何才能调用父级mycomponentHeader内部的引用my-component?我试过这样调用裁判:
console.log(this.$parent.$refs.mycomponentHeader)
console.log(this.$refs.mycomponentHeader)
console.log(this.$refs)
console.log(this.$children.$refs.mycomponentHeader)
Run Code Online (Sandbox Code Playgroud)
但这些导致了一个未定义的空对象,并且无法读取未定义的属性(读取“$refs”)。任何帮助,将不胜感激!
您可以简单地通过将 a 分配给子组件元素,然后从父组件ref访问子组件内部变量来实现这一点。ref
在父组件模板中:
<parent-component>
<child-component ref="childComponent"/>
<parent-component>
Run Code Online (Sandbox Code Playgroud)
在脚本中:
mounted() {
console.log(this.$refs.childComponent) // Here you can access any properties or methods of a child component.
}
Run Code Online (Sandbox Code Playgroud)
现场演示:
<parent-component>
<child-component ref="childComponent"/>
<parent-component>
Run Code Online (Sandbox Code Playgroud)
mounted() {
console.log(this.$refs.childComponent) // Here you can access any properties or methods of a child component.
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9592 次 |
| 最近记录: |