Finding a Specific Parent Vue Component

Posted on Updated on Vue.js by Gergő D. Nagy

In some cases, we have to nest components, and yet to communicate with a specific parent component, however, we can’t use the $parent prop, because we don’t know the depth of the nesting. Let’s see a solution where we can easily target a specific parent component to hunt them down.

Let’s imagine a data form component that has to communicate with a child input component. However, the form can contain any other element as well, not only input-like fields. Let’s say in the input component we need to use some of the form’s functionality – like error handling, etc. –, so we need to find the form component and use it somehow.

We can use computed properties for that and a simple while loop. Take a look at a simple solution:

// Input.vue

computed: {
    form() {
        let parent = this.$parent;

        while (parent && parent.$options._componentTag !== 'data-form') {
            parent = parent.$parent;
        }

        return parent;
    }
}

Form this point, we can access easily the form component, wherever it’s located. We can use any method or listen to events, it’s like just using the $root or the $parent props.

// Input.vue

this.form.$on('change', ...);

And that’s it. This is a simple yet useful implementation to track a specific parent component if we don’t know the relative positions of the two components.

Need a web developer? Maybe we can help, get in touch!