How to get data from the child component in Vue

In this short post, we will see how we can access data from the child component in Vue JS.

To get access to data from the child component, we can use the $ref attribute in Vue.

Let’s say we have two components :

  1. App.vue (Parent component)
  2. Child.vue (Child Compnent)

Now in the child component, we have some data properties. For Example

<template>
  <div class="child">Child Component Hello</div>
</template>

<script>
export default {
  data() {
    return {
      name: "Jake",
      age: 25
    };
  },
};
</script>

Next, we will import this child component to App.vue i.e the parent component. And will try to get the data i.e the name and age from it.

<template>
  <div id="app">
    <Child ref="child" />
    <button @click="getData()">Get Data</button>
  </div>
</template>

<script>
import Child from "./components/Child";

export default {
  components: {
    Child,
  },
  methods: {
    getData() {
      const data = this.$refs.child.name;
      console.log(data);
    },
  },
};
</script>

So, to access the data from our child component we will use the $ref attribute.

In Vue, $ref acts similar to a key attribute, it allows us to obtain a reference to the specific DOM element.

So, the get the name data from the child component we will use this.$refs.child.name . It will return us the name i.e ‘Jake’ and display it on the console.

Demo Code:

Edit get-data-from-child-vue

Related Topics:

How to pass data from child to parent component in Vue JS

How to pass data from parent component to child using props in Vue

Execute a function from child component in Vue

Scroll to Top