Search code examples
javascriptvue.jsvuejs2vue-componentvuejs3

Vue 3: Emit event from parent to child component


Now I need to emit event from parent to child component. I see in vue version 3 $on, $off and $once instance methods are removed. Application instances no longer implement the event emitter interface.

How now I can emit events from parent component and listen from child component in vue version 3?


Solution

  • You can access to child methods by using Refs

    https://v3.vuejs.org/guide/composition-api-template-refs.html

    <!-- Parent -->
    <template>
        <ChildComponent ref="childComponentRef" />
    </template>
    
    <script>
    import { ref } from 'vue'
    import ChildComponent from './components/ChildComponent.vue'
    
    export default { 
      setup( ) {
        const childComponentRef = ref()
        childComponentRef.value.expandAll();
    
        return { childComponentRef }
      }
    }
    </script>
    
    <!-- Child -->
    <script>
    export default {
        setup() {
            const expandAll= () => {
                //logic...
            }
    
            return { expandAll}
        }
    }
    </script>