如何在父事件上调用子组件上的函数 [英] How to call function on child component on parent events
问题描述
在Vue 2.0文档和其他清楚地表明从父母到孩子的沟通是通过道具进行的。
In Vue 2.0 the documentation and others clearly indicate that communication from parent to child happens via props.
父母如何告诉孩子通过道具发生的事件?
How does a parent tell its child an event has happened via props?
我应该只看一个名为事件的道具吗?这感觉不对, $ emit / $ on
也不适合从孩子到父母,以及hub模型适用于远程元素。)
Should I just watch a prop called event? That doesn't feel right, nor do alternatives ($emit
/$on
is for child to parent, and a hub model is for distant elements).
我有一个父容器,它需要告诉它子容器,可以在API上执行某些操作。 我需要能够触发功能。
I have a parent container and it needs to tell its child container that it's okay to engage certain actions on an API. I need to be able to trigger functions.
推荐答案
为子组件提供 ref
并使用 $ refs
直接调用子组件上的方法。
Give the child component a ref
and use $refs
to call a method on the child component directly.
html:
<div id="app">
<child-component ref="childComponent"></child-component>
<button @click="click">Click</button>
</div>
javascript:
javascript:
var ChildComponent = {
template: '<div>{{value}}</div>',
data: function () {
return {
value: 0
};
},
methods: {
setValue: function(value) {
this.value = value;
}
}
}
new Vue({
el: '#app',
components: {
'child-component': ChildComponent
},
methods: {
click: function() {
this.$refs.childComponent.setValue(2.0);
}
}
})
有关详细信息,请参阅关于参考的Vue文档。
For more info, see Vue documentation on refs.
这篇关于如何在父事件上调用子组件上的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!