如何从 vue.js 中的父级访问子方法 [英] How to access to a child method from the parent in vue.js

查看:34
本文介绍了如何从 vue.js 中的父级访问子方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个嵌套组件,从父级访问子方法的正确方法是什么?

this.$children[0].myMethod() 似乎可以解决问题,但它非常丑陋,不是吗,还有什么更好的方法:

解决方案

您可以使用 ref.

从 './components/ChildForm' 导入 ChildForm新的 Vue({el: '#app',数据: {物品: {}},模板:`<div><ChildForm :item="item" ref="form"/><button type="submit" @click.prevent="submit">发布</button>

`,方法: {提交() {this.$refs.form.submit()}},组件:{ ChildForm },})

如果你不喜欢紧耦合,你可以使用事件总线 如@Yosvel Quintero 所示.下面是另一个通过将总线作为 props 传入来使用事件总线的示例.

从 './components/ChildForm' 导入 ChildForm新的 Vue({el: '#app',数据: {物品: {},总线:新的Vue(),},模板:`<div><ChildForm :item="item" :bus="bus" ref="form"/><button type="submit" @click.prevent="submit">发布</button>

`,方法: {提交() {this.bus.$emit('提交')}},组件:{ ChildForm },})

组件代码.