【问题标题】:vue running function in child component from parent componentvue 在父组件的子组件中运行函数
【发布时间】:2018-08-11 02:54:33
【问题描述】:

我有一个带按钮的父组件

<btn @click="validate">Run child method - and validate something!</btn>
<child-component></child-component>

我有一个子组件,它有一个方法:

methods:{
   validate () {...}
}

我想从我的父组件调用这个方法。怎么做?

给定的解决方案有什么优点/缺点吗?

【问题讨论】:

标签: vue.js


【解决方案1】:

您可以添加属性 ref 并使用 ref 值来访问组件/调用其方法。

<child-component ref="child" ></child-component>


this.$refs.child.validate();

https://vuejs.org/v2/guide/components.html#Child-Component-Refs

尽管存在道具和事件,但有时你可能仍然 需要在 JavaScript 中直接访问子组件。达到 这您必须使用为子组件分配参考 ID 参考。例如:

var parent = new Vue({ el: '#parent' }) // 访问子组件 instance var child = parent.$refs.profile

在你的情况下:&lt;btn @click="$refs.child.validate()"&gt;Run child method - and validate something!&lt;/btn&gt;

【讨论】:

    猜你喜欢
    • 2021-09-10
    • 1970-01-01
    • 2019-05-05
    • 2017-04-29
    • 1970-01-01
    • 2020-10-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多