如何在父事件上调用子组件的函数 [英] How to call function on child component on parent events

查看:24
本文介绍了如何在父事件上调用子组件的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Vue 2.0 中,文档和 others 很清楚表示父母与孩子之间的交流是通过道具进行的.

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?

我应该只看一个名为 event 的道具吗?这感觉不对,替代方案也不对($emit/$on 用于子级到父级,集线器模型用于远距离元素).

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);
    }
  }
})

有关详细信息,请参阅 关于 refs 的 Vue 文档.

For more info, see Vue documentation on refs.

这篇关于如何在父事件上调用子组件的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆