Vue JS Unable to get values of data attributes in child component
When working with Vue.js, you might encounter situations where you want to access data properties from a parent component in a child component. However, directly accessing data properties from a child component using the $parent
or $props
properties might not work as expected. Instead, you should use a prop to pass data from the parent to the child component.
Here's a step-by-step guide to help you understand how to pass data from a parent component to a child component in Vue.js:
- Define the data property in the parent component:
// Parent component
export default {
data() {
return {
parentData: 'Parent data'
}
}
}
- Pass the data property as a prop to the child component:
// Parent component
export default {
data() {
return {
parentData: 'Parent data'
}
},
methods: {
passDataToChild() {
this.$refs.childComponent.receiveData(this.parentData);
}
},
components: {
ChildComponent
}
}
- Define the child component:
// Child component
export default {
props: ['dataFromParent'],
methods: {
receiveData(data) {
this.childData = data;
}
},
data() {
return {
childData: ''
}
}
}
- Use the child component in the parent component and pass the data property as a prop:
// Parent component template
<template>
<button @click="passDataToChild">Pass data to child</button>
<child-component ref="childComponent" :data-from-parent="parentData"></child-component>
</template>
- Access the data property in the child component using the
props
property:
// Child component
export default {
props: ['dataFromParent'],
data() {
return {
childData: ''
}
},
methods: {
receiveData(data) {
this.childData = data;
}
},
created() {
this.childData = this.dataFromParent;
}
}
Now, when you click the button in the parent component, the parentData
will be passed to the child component as a prop, and you can access it directly in the child component using the dataFromParent
prop or by assigning it to the childData
property in the created
hook.
By following these steps, you can effectively pass data from a parent component to a child component in Vue.js.