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

前端 未结 4 1958
深忆病人
深忆病人 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 00:40

    Ref and event bus both has issues when your control render is affected by v-if. So, I decided to go with a simpler method.

    The idea is using an array as a queue to send methods that needs to be called to the child component. Once the component got mounted, it will process this queue. It watches the queue to execute new methods.

    (Borrowing some code from Desmond Lua's answer)

    Parent component code:

    import ChildComponent from './components/ChildComponent'
    
    new Vue({
      el: '#app',
      data: {
        item: {},
        childMethodsQueue: [],
      },
      template: `
      
    `, methods: { submit() { this.childMethodsQueue.push({name: ChildComponent.methods.save.name, params: {}}) } }, components: { ChildComponent }, })

    This is code for ChildComponent

    
    
    
    

    And there is a lot of room for improvement like moving processMethodsQueue to a mixin...

提交回复
热议问题