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
JavaScript
x
27
27
1
<template>
2
<div>
3
<Child v-bind:exampleData="exampleData" />
4
</div>
5
</template>
6
7
<script>
8
import Child from "./Child.vue";
9
export default {
10
name: "Parent",
11
components: {
12
Child,
13
},
14
data() {
15
return {
16
exampleData: [],
17
};
18
},
19
20
async created() {
21
const exampleData = await fetchData();
22
this.exampleData = exampleData
23
},
24
25
};
26
</script>
27
Child
JavaScript
1
24
24
1
<template>
2
<div><!-- show result data here --></div>
3
</template>
4
5
<script>
6
export default {
7
name: "Child",
8
props: ["exampleData"],
9
10
async created() {
11
let abc = this.exampleData;
12
// abc is undefined
13
const resultData = await fetData(abc);
14
this.result = resultData;
15
},
16
17
data() {
18
return {
19
result: [],
20
};
21
},
22
23
};
24
Advertisement
Answer
Try to use mounted()
method instead of created()
like this:
JavaScript
1
21
21
1
<template>
2
<div><!-- show result data here --></div>
3
</template>
4
5
<script>
6
export default {
7
name: "Child",
8
props: ["exampleData"],
9
async mounted() {
10
let abc = this.exampleData;
11
// abc is undefined
12
const resultData = await fetData(abc);
13
this.result = resultData;
14
},
15
data() {
16
return {
17
result: [],
18
};
19
},
20
};
21
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:
JavaScript
1
21
21
1
<template>
2
<div><!-- show result data here --></div>
3
</template>
4
5
<script>
6
export default {
7
name: "Child",
8
props: ["exampleData"],
9
data() {
10
return {
11
result: [],
12
};
13
},
14
watch: {
15
exampleData() {
16
const resultData = await fetData(this.exampleData);
17
this.result = resultData;
18
}
19
}
20
};
21