Vuejs Child component $refs - What are they good for?

Child component refs are somewhat documented in the offical documentation. But it doesn't really show you what or why you might need to do this. I have found that utilizting child component refs a somewhat edge case,but very useful.
so creating them can be as simple as:

$refs, while used on a normal HTML element will give you the DOM node, creating a ref on a component will give you direct access to its Vue instance allowing you to call methods, access properties etc.


export default {
    methods: {
        callChildComponentMethod() {
           this.$refs.myCompInstance.deleteSomething();
       },
       accessChildComponentData() {
           this.$refs.myCompInstance.someDataField.
       }
    }
}

This can really be useful, in my own cases instead of having to pass function refs back and forth between the parent and child as props. But just keep in mind the warning the offical documentation points out

$refs are only populated after the component has been rendered, and it is not reactive. It is only meant as an escape hatch for direct child manipulation - you should avoid using $refs in templates or computed properties.

Comments