How to access to a child method from the parent in vue.js

前端 未结 4 1951
深忆病人
深忆病人 2020-11-30 00:33

I have two nested components, what is the proper way to access to the child methods from the parent ?

this.$children[0].myMethod() seems to do the trick

4条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-30 01:01

    Parent-Child communication in VueJS

    Given a root Vue instance is accessible by all descendants via this.$root, a parent component can access child components via the this.$children array, and a child component can access it's parent via this.$parent, your first instinct might be to access these components directly.

    The VueJS documentation warns against this specifically for two very good reasons:

    • It tightly couples the parent to the child (and vice versa)
    • You can't rely on the parent's state, given that it can be modified by a child component.

    The solution is to use Vue's custom event interface

    The event interface implemented by Vue allows you to communicate up and down the component tree. Leveraging the custom event interface gives you access to four methods:

    1. $on() - allows you to declare a listener on your Vue instance with which to listen to events
    2. $emit() - allows you to trigger events on the same instance (self)

    Example using $on() and $emit():

    const events = new Vue({}),
        parentComponent = new Vue({
          el: '#parent',
          ready() {
            events.$on('eventGreet', () => {
              this.parentMsg = `I heard the greeting event from Child component ${++this.counter} times..`;
            });
          },
          data: {
            parentMsg: 'I am listening for an event..',
            counter: 0
          }
        }),
        childComponent = new Vue({
          el: '#child',
          methods: {
          greet: function () {
            events.$emit('eventGreet');
            this.childMsg = `I am firing greeting event ${++this.counter} times..`;
          }
        },
        data: {
          childMsg: 'I am getting ready to fire an event.',
          counter: 0
        }
      });
    
    
    

    Parent Component

    {{parentMsg}}

    Child Component

    {{childMsg}}

    Answer taken from the original post: Communicating between components in VueJS

提交回复
热议问题