How to get data from the child component in Vue
Find out how to get or access the data from the child component using the $ref directory 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 :
- App.vue (Parent component)
- 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:
<a href="https://codesandbox.io/s/get-data-from-child-vue-cnmoj3?fontsize=14&hidenavigation=1&theme=dark"> <img alt="Edit get-data-from-child-vue" src="https://codesandbox.io/static/img/play-codesandbox.svg"> </a>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
Related Posts
Easy Way to use localStorage with Vue
Short article on how to use local storage with Vue and learn saving and storing data in local storage with the setItem() and getItem() methods.
Force update Vue to Reload/Rerender component
Short tutorial on how to correctly force update Vue.js component to reload or rerender. The component is reinitialized without having to do a browser refresh.
Set and get cookies in a browser in Vue App
Find out how to set and get cookies in a browser for your webpage in Vue using vue-cookies package.
Save vuex state after page refresh in Vue App
Short tutorial on how to save (or persist) data in a vue application using Vuex and vuex-persist npm package.
