Retrieving child component's data property in Vue 3 using TypeScript and Composition API

I have set up two components: a parent and a child.

App.vue //Parent

<template>
  <div class="common-layout">
    <Container>
      <Header><center>Vue JS 3 (Composition API and )</center></Header>
      <Main>
        <BookForm ref="bookRef" />
        <p v-if="bookRef">{{ bookRef }}</p>
      </Main>
    </Container>
  </div>
</template>
<script setup lang="ts"">
  import BookForm from "./components/organism/bookForm/index.vue"
  import { ref } from "vue"
  import {
    ElContainer as Container,
    ElHeader as Header,
    ElMain as Main,
  } from "element-plus"

  const bookRef = ref<InstanceType<typeof BookForm>>()
</script>

BookForm.vue //Child

<template>
  <Row span="20">
    <Column :span="12" :offset="6">
      <!-- <HelloWorld /> -->
      <Form label-position="top">
        <Input label="Title" v-model="title" />
        <Input label="Price" v-model="price" />
        <Button label="Add" type="success" :onClick="addBook" />
      </Form>
    </Column>
  </Row>
</template>
<script setup lang="ts">
  import { ElRow as Row, ElCol as Column, ElForm as Form } from "element-plus"
  import HelloWorld from "@/components/HelloWorld.vue"
  import Input from "@/components/atom/input/index.vue"
  import Button from "@/components/atom/button/index.vue"
  import { reactive, ref } from "vue"

  interface IBook {
    title: string
    price: string | number
  }
  const books = reactive<IBook[]>([])
  const title = ref<string>("")
  const price = ref<string | number>("")

  const addBook = () => {
    books.push({ title: title.value, price: price.value })
    title.value = ""
    price.value = ""
  }
</script>

I came across this thread on Vue Forum for a solution, but I am unable to retrieve data from the child component into the parent component.

When I console log console.log(bookRef.value), it returns undefined. What is the correct way to access child component's data using TypeScript and the composition API setup tag?

Answer №1

Take advantage of defineexpose in order to expose the properties of the child component to the parent component :

<script setup lang="ts">
  import { ElRow as Row, ElCol as Column, ElForm as Form } from "element-plus"
  import HelloWorld from "@/components/HelloWorld.vue"
  import Input from "@/components/atom/input/index.vue"
  import Button from "@/components/atom/button/index.vue"
  import { reactive, ref, defineExpose } from "vue"

  interface IBook {
    title: string
    price: string | number
  }
  const books = reactive<IBook[]>([])
  const title = ref<string>("")
  const price = ref<string | number>("")

  const addBook = () => {
    books.push({ title: title.value, price: price.value })
    title.value = ""
    price.value = ""
  }

defineExpose({
  books, title, price, addBook
})
</script>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The d3.js circles mysteriously disappear when attempting to implement the update pattern

I find myself in a challenging situation once again - there may come a day when I am the one offering help, but for now, I admit that I am feeling quite lost. I am very new to d3.js and my understanding of JavaScript is still quite basic. My current proje ...

What is the best way to manage the back button functionality on pages that use templates?

I am currently developing a website using angularjs. The layout consists of two main sections: the menu and the content area. For instance This is an example page: /mainpage <div> <div id="menu"> <div ng-click="setTemplate('fi ...

You should be providing a string value as expected. It seems that you may have overlooked exporting your component from the correct file it was defined in, or perhaps there is confusion with default and named

I encountered a strange error despite meticulously organizing and exporting/importing files. The code is structured from components to the App render method. Item.js import React from 'react'; import './Global.css' const Item = ({data ...

Ways to stop the location object from resetting in ReactJS when reloading the page

Currently, I am using Link to redirect and call another component. The code looks something like this: <Link to={{ pathname: "/app/" + app.appId, appDetail: { app: app } }}>> When I call the path /app/:appId, it triggers the AppDetails ...

Using Rxjs to reset an observable with combineLatest

My scenario involves 4 different observables being combined using "combineLatest". I am looking for a way to reset the value of observable 2 if observables 1, 3, or 4 emit a value. Is this possible? Thank you! Mat-table sort change event (Sort class) Mat- ...

What is the best way to create a method that waits for a POST request to complete?

I have the following code snippet: login() { const body = JSON.stringify({ "usuario":"juanma", "password":"1234"}); console.log(body); let tokencito:string = '' const params = ne ...

Retrieving multiple checkbox values from the front end using AJAX and passing them to

I have some code for ajax that is causing me issues. Here it is: var userCheckbox = $("input[name=chk]:checked").val(); This is the checkbox section in my html: <input id="checkbx" type="checkbox" name="chk" value="apple"/>apple</td> <inp ...

JavaScript: A timer that relies solely on the concept of TIME

Hello all, I have a specific question regarding starting a timer in JavaScript for a test scenario. Despite researching on my own and seeking help on various platforms, I haven't found a solution that fits my requirements. I am looking to implement a ...

You have the ability to effortlessly upload multiple images in just one request using the valums-file-uploader feature

While working with dropzone.js, I discovered that it offers the option to upload multiple images in a single ajax request by setting parallelUploads to define the number of images and uploadMultiple to true to upload all at once. parallelUploads // set th ...

Troubleshooting issues with sending POST requests in node.js

I've been attempting to initiate a post request, but for some reason, it's not going through. Strangely, I'm not seeing any output in the console log of my browser. My node server.js is up and running on x.x.x.x:8000. I've connected it ...

Avoid page refreshing when modifying app.js in React

Today is only my second day using React and I started by creating a React app with "npx create-react-app." However, when I tried to make changes to the app.js file, they didn't appear on the page even after refreshing the browser multiple times. (My n ...

What is the best way to extract information from an API using javascript?

I've been working on a weather app project, and recently made changes to the code so that the longitude and latitude values are based on the user's geolocation. However, I've encountered an issue where the button is no longer functioning. Up ...

Issues persist with debugger functionality in browser development tools following an upgrade from Angular 8 to version 15

After upgrading from Angular version 8 to version 15, I've encountered an issue where the debugger is not functioning in any browser's developer tools. Can anyone provide some insight on what could be causing this problem? Is it related to the so ...

The Ejs page is failing to render on the simplified code version

Here is the code that displays the 'post' page: app.get("/posts/:postName", function(req, res) { const requestedTitle = _.lowerCase(req.params.postName); posts.forEach(function(post) { const storedTitle = _.lowerCase(post.title ...

Steps for running a function upon activation of a React Router:

I'm currently using Reacter Router to manage the routes of my application. For authentication, I am utilizing an OAuth system that provides my application with the following URL: http://localhost/login-meli?code=1234567890 Every time this particular ...

Tips for silencing the microphone on vue-webrtc

Currently, I am utilizing the vue-webrtc component from here. My objective is to create a button that allows me to mute my local microphone, as well as another button to unmute it. Can anyone provide guidance on how to achieve this functionality? I am at ...

What causes the text-align property to function in varying ways across different tags?

Can you explain why the text-align property behaves differently on different tags? In two cases, I am trying to center my text. In the first case, I use a parent div tag with an anchor tag inside. When I need to center align, I apply the property to the p ...

Flow bar for micro-tasks

In my current project, I am faced with the task of organizing a series of 4 mini tasks and displaying to the end user which specific mini task they are currently on. To accomplish this, I have been utilizing image tags for each task. <img>1</img ...

Passing PHP Variables Between Pages

I'm currently working on building a game using html5(phaser js) and I need to create a leaderboard. Here's the code snippet I have: restart_game: function() { // Start the 'main' state, which restarts the game //this.game.time.events ...

"Unexpected behavior observed with jQuery's $.extend method - functions not returning as

For a project I'm working on, I have integrated gmail.js. Within this library, there is a function structured as follows: api.dom.compose = function(element) { // operations } api.dom.email = function(element) { this.id = element; var me ...