I’ve been having trouble with Nuxt2.15 (Vue.js). I want to send the data from parent component to child component that parent components fetched. And, I want to fetch another data from a child component by useing the data from the parent component. But props data is undefined in the child component. I tried to use “watch” and “computed” in the child component. But I couldn’t make it work. I would appreciate it if someone can show me how to fix it.
Parent
<template> <div> <Child v-bind:exampleData="exampleData" /> </div> </template> <script> import Child from "./Child.vue"; export default { name: "Parent", components: { Child, }, data() { return { exampleData: [], }; }, async created() { const exampleData = await fetchData(); this.exampleData = exampleData }, }; </script>
Child
<template> <div><!-- show result data here --></div> </template> <script> export default { name: "Child", props: ["exampleData"], async created() { let abc = this.exampleData; // abc is undefined const resultData = await fetData(abc); this.result = resultData; }, data() { return { result: [], }; }, };
Advertisement
Answer
Try to use mounted()
method instead of created()
like this:
<template> <div><!-- show result data here --></div> </template> <script> export default { name: "Child", props: ["exampleData"], async mounted() { let abc = this.exampleData; // abc is undefined const resultData = await fetData(abc); this.result = resultData; }, data() { return { result: [], }; }, };
But, if the data passed from the parent is asynchronous or could be changed at some moment, I would recommend using the watch prop like this:
<template> <div><!-- show result data here --></div> </template> <script> export default { name: "Child", props: ["exampleData"], data() { return { result: [], }; }, watch: { exampleData() { const resultData = await fetData(this.exampleData); this.result = resultData; } } };