如何从 vue.js 中的父级访问子方法 [英] How to access to a child method from the parent in 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 },})
组件代码.
...模板><脚本>导出默认{name: 'NowForm',道具:['物品','公共汽车'],方法: {提交() {...}},安装(){this.bus.$on('提交', this.submit)},}
https://code.luasoftware.com/tutorials/vuejs/parent-call-child-component-method/
I have two nested components, what is the proper way to access to the child methods from the parent ?
this.$children[0].myMethod()
seems to do the trick but it is pretty ugly, isn't it, what can be better way:
<script>
import child from './my-child'
export default {
components: {
child
},
mounted () {
this.$children[0].myMethod()
}
}
</script>
You can use ref.
import ChildForm from './components/ChildForm'
new Vue({
el: '#app',
data: {
item: {}
},
template: `
<div>
<ChildForm :item="item" ref="form" />
<button type="submit" @click.prevent="submit">Post</button>
</div>
`,
methods: {
submit() {
this.$refs.form.submit()
}
},
components: { ChildForm },
})
If you dislike tight coupling, you can use Event Bus as shown by @Yosvel Quintero. Below is another example of using event bus by passing in the bus as props.
import ChildForm from './components/ChildForm'
new Vue({
el: '#app',
data: {
item: {},
bus: new Vue(),
},
template: `
<div>
<ChildForm :item="item" :bus="bus" ref="form" />
<button type="submit" @click.prevent="submit">Post</button>
</div>
`,
methods: {
submit() {
this.bus.$emit('submit')
}
},
components: { ChildForm },
})
Code of component.
<template>
...
</template>
<script>
export default {
name: 'NowForm',
props: ['item', 'bus'],
methods: {
submit() {
...
}
},
mounted() {
this.bus.$on('submit', this.submit)
},
}
</script>
https://code.luasoftware.com/tutorials/vuejs/parent-call-child-component-method/
这篇关于如何从 vue.js 中的父级访问子方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!