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

前端 未结 4 1961
深忆病人
深忆病人 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:43

    You can use ref.

    import ChildForm from './components/ChildForm'
    
    new Vue({
      el: '#app',
      data: {
        item: {}
      },
      template: `
      
    `, methods: { submit() { this.$refs.form.submit() } }, components: { ChildForm }, })

    If you dislike tight coupling, you can use Event Bus as shown by @Yosvel Quintero. Below is another example of using event bus by passing in the bus as props.

    import ChildForm from './components/ChildForm'
    
    new Vue({
      el: '#app',
      data: {
        item: {},
        bus: new Vue(),
      },
      template: `
      
    `, methods: { submit() { this.bus.$emit('submit') } }, components: { ChildForm }, })

    Code of component.

    
    
    
    

    https://code.luasoftware.com/tutorials/vuejs/parent-call-child-component-method/

提交回复
热议问题