Categories
Vue Answers

How to access nested child components using refs with Vue.js?

Spread the love

Sometimes, we want to access nested child components using refs with Vue.js.

In this article, we’ll look at how to access nested child components using refs with Vue.js.

How to access nested child components using refs with Vue.js?

To access nested child components using refs with Vue.js, we can use the $refs property of the parent component.

For instance, in the parent component, we write

<template>
  <div id="app">
    <my-component ref="myFirstLevelRefName"></my-component>
  </div>
</template>

Then in the child component, we write

<template>
  <div>
    <input ref="mySecondLevelRefName" value="Hello" />
  </div>
</template>

Then back in the parent component, we can access the input in the child component by writing

<script>
//...
export default {
  //...
  mounted() {
    console.log(
      this.$refs.myFirstLevelRefName.$refs.mySecondLevelRefName.value
    );
  },
  //...
};
</script>

We use this.$refs.myFirstLevelRefName.$refs.mySecondLevelRefName to get the input element in the child component from the parent component.

And then we get the input’s value with the value property.

Conclusion

To access nested child components using refs with Vue.js, we can use the $refs property of the parent component.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *