I have setup two components parent and child:
App.vue //Parent
JavaScript
x
23
23
1
<template>
2
<div class="common-layout">
3
<Container>
4
<Header><center>Vue JS 3 (Composition API and )</center></Header>
5
<Main>
6
<BookForm ref="bookRef" />
7
<p v-if="bookRef">{{ bookRef }}</p>
8
</Main>
9
</Container>
10
</div>
11
</template>
12
<script setup lang="ts">
13
import BookForm from "./components/organism/bookForm/index.vue"
14
import { ref } from "vue"
15
import {
16
ElContainer as Container,
17
ElHeader as Header,
18
ElMain as Main,
19
} from "element-plus"
20
21
const bookRef = ref<InstanceType<typeof BookForm>>()
22
</script>
23
BookForm.vue //child
JavaScript
1
34
34
1
<template>
2
<Row span="20">
3
<Column :span="12" :offset="6">
4
<!-- <HelloWorld /> -->
5
<Form label-position="top">
6
<Input label="Title" v-model="title" />
7
<Input label="Price" v-model="price" />
8
<Button label="Add" type="success" :onClick="addBook" />
9
</Form>
10
</Column>
11
</Row>
12
</template>
13
<script setup lang="ts">
14
import { ElRow as Row, ElCol as Column, ElForm as Form } from "element-plus"
15
import HelloWorld from "@/components/HelloWorld.vue"
16
import Input from "@/components/atom/input/index.vue"
17
import Button from "@/components/atom/button/index.vue"
18
import { reactive, ref } from "vue"
19
20
interface IBook {
21
title: string
22
price: string | number
23
}
24
const books = reactive<IBook[]>([])
25
const title = ref<string>("")
26
const price = ref<string | number>("")
27
28
const addBook = () => {
29
books.push({ title: title.value, price: price.value })
30
title.value = ""
31
price.value = ""
32
}
33
</script>
34
I’ve followed this thread from vue forum for the solution but I cannot retrieve data from child component into parent component.
When I console log console.log(bookRef.value)
I get undefined
. What is the correct way to get child component’s data with typescript and composition api setup
tag ?
Advertisement
Answer
Try to use defineexpose
to expose the child component properties to the parent one :
JavaScript
1
26
26
1
<script setup lang="ts">
2
import { ElRow as Row, ElCol as Column, ElForm as Form } from "element-plus"
3
import HelloWorld from "@/components/HelloWorld.vue"
4
import Input from "@/components/atom/input/index.vue"
5
import Button from "@/components/atom/button/index.vue"
6
import { reactive, ref,defineExpose } from "vue"
7
8
interface IBook {
9
title: string
10
price: string | number
11
}
12
const books = reactive<IBook[]>([])
13
const title = ref<string>("")
14
const price = ref<string | number>("")
15
16
const addBook = () => {
17
books.push({ title: title.value, price: price.value })
18
title.value = ""
19
price.value = ""
20
}
21
22
defineExpose({
23
books, title, price, addBook
24
})
25
</script>
26