I have encountered an issue while using vue.js with defineComponent.
My goal is to obtain data and pass it to child components, but unfortunately the data turns out to be undefined.
parent
<template>
<Child :data="user"/>
<div>{{ user.name }}</div> <!-- It works here -->
</template>
export default defineComponent({
setup() {
const user = ref({});
const getData = () => {
// takes 3 seconds
user.value = data;
}
return {user}
}
})
child
<template>
<div>{{ user.name }}</div> <!-- TypeError Cannot read properties of undefined -->
</template>
export default defineComponent({
props: {
data: { type: Object },
},
setup(props) {
const user = ref(props.data);
return {user}
}
})
After implementing watch in the child component, the issue was resolved. Is this the correct approach to solve such problems?
child
export default defineComponent({
props: {
data: { type: Object },
},
setup(props) {
const user = ref({});
watch(props, (n, o) => user.value = props.data)
}
})