我有一个带按钮的父组件
<btn @click="validate">Run child method - and validate something!</btn>
<child-component></child-component>
我有一个子组件,它有一个方法:
methods:{
validate () {...}
}
我想从我的父组件调用此方法。怎么做?
给定解决方案是否存在任何利弊?
答案 0 :(得分:2)
您可以添加属性ref并使用ref值访问组件/调用其方法。
<child-component ref="child" ></child-component>
this.$refs.child.validate();
https://vuejs.org/v2/guide/components.html#Child-Component-Refs
尽管存在道具和事件,但有时你可能仍然存在 需要在JavaScript中直接访问子组件。实现 这个你必须使用引用子组件的引用ID REF。例如:
var parent = new Vue({el:&#39;#parent&#39;})//访问子组件 instance var child = parent。$ refs.profile
在您的情况下:<btn @click="$refs.child.validate()">Run child method - and validate something!</btn>