How to get data from the child component in Vue

featured Image

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

Related Posts

featured Image

How to add common header and footer in vuejs.

Here, in this article, we will learn how to add a common header and footer component in our vuejs application. In general, we always have the same header and footer…

Read more
featured Image

How to call a function in VUE template?

Here, we will learn on how to call a function in vue template. First, we have to define the function in the methods. and then we can use an event…

Read more
featured Image

How to redirect to external url in vue

Here, we will learn how to redirect to an external URL in vuejs application. Page Navigation is one of the basic features of a website. It helps us to navigate…

Read more

Leave a Reply

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