Home>

I want to call a method set on a child component from a parent.

In the opposite case, I would like to use $emit, but how can I call a child method from a parent? Or shouldn't you do that in the first place? Thank you.

  • Answer # 1

    For small things, you can also call child component methods with $refs likethis. $refs.foo.bar ().
    However, direct data reference between components is not recommended.

    Component-Vue.js

      

    However, it is also very important to keep the parent and child as separated as possible through a well-defined interface. This ensures that the code for each component is written and judged relatively independently. Therefore, components can be made more maintainable and potentially reusable

    So basically

    $emit from child to parent

    Parent to child props

    It may be good to pass data with

    .

    However, props cannot directly call child component methods.
    Therefore, there is a way to use EventBus as shown below to coordinate processing between components.

    Communication other than parent-child

    var EventBus = new Vue ()
    Object.defineProperties (Vue.prototype, {
        $bus: {
            get () {
                return EventBus
            }
        }
    }
    let ComponentY = Vue.extend ({
      mounted () {
        this. $bus. $on ('onMountedX', () =>{
            console.log ('onMountedX')
        })
      }
    })
    let ComponentX = Vue.extend ({
      mounted () {
        this. $bus. $emit ('onMountedX')
      }
      components: [ComponentY]
    })

    However, if you want to make something larger, it is better to manage the state with something like vuex.

  • Answer # 2

    Looks good with ref

    Use vuex for more complex

  • Answer # 3

    If you allow child components to be referenced with the ref attribute, you can call child methods from the parent
    The following is a sample program.
    The test method of the parent component App.vue calls the method of the child component Test.vue using $refs.

    App.vue

    <template>
      <div id = "app">
        <test ref = "test"></test>
        <button @ click = "test">test</button>
      </div>
    </template>
    <script>
    import Test from "./Test.vue"
    export default {
      methods: {
        test () {
          console.log ("parentMethod")
          this. $refs.test.childMethod ()
        },
      },
      components: {Test}
    }
    </script>

    Test.vue

    <template>
        <p>test</p>
    </template>
    <script>
    export default {
        methods: {
            childMethod () {
                console.log ("childMethod")
            }
        }
    }
    </script>