I have a question.
I use vue.js with defineComponent.
I want to get data and pass the data to child components but the data is 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}
}
})
If I use watch in child component, It works.
Is it correct to write a code like this?
child
export default defineComponent({
props: {
data: { type: Object },
},
setup(props) {
const user = ref({});
watch(props, (n, o) => user.value = props.data)
}
})