如何在父事件上调用子组件的函数

2022-01-15 00:00:00 event-handling javascript vue.js vuejs2

在 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.

相关文章