Vue 3 - Child Component Script Not Updating with Reactive Prop Changes

I am facing an issue where I am trying to pass a reactive data as a prop to a child component in Vue 3. The data updates correctly in the child component's template, but it does not reflect in the child component's script. In the parent component:

<script setup lang="ts">
import { ref } from 'vue'

const someDataId = ref<number | null>()

const someFunction = (id) => {
    someDataId.value = id
}
</script>

<template>
<ChildComponent :dataId="someDataId" />
</template>

In the child component:

<script setup lang="ts">
const { dataId } = defineProps<{
    dataId: number | null | undefined
}>()

console.log(dataId)
</script>

<template>
{{ dataId }}
</template>

Even though the dataId prop updates correctly in the template, it appears as undefined when displayed in the console.

I have tried handling props within the onUpdated and watch functions, but the issues persist. When using onUpdated, the dataId remains undefined, and with watch, nothing is logged to the console because it seems like no changes are being detected. Using nextTick has also proved ineffective.

If anyone has insights or solutions on how to resolve this issue, your help would be greatly appreciated. Thank you!

Answer №1

To ensure the script content is executed only once at creation time, it's recommended to use a watcher as shown below. Additionally, avoid destructing the props to maintain reactivity:

<script setup lang="ts">
import {watch} from 'vue'

const props = defineProps<{
    dataId: number | null | undefined
}>()

watch(()=>props.dataId, (newVal)=>{
  console.log(newVal)
},{
immediate:true
})

</script>

<template>
{{ dataId }}
</template>

In Vue 3.3, you have the option to destruct props, but please note that this feature is still experimental.

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

What are the best practices for utilizing intro.js effectively on mobile devices?

Description When using introjs on mobile devices with a screen width of less than 600px, the tooltip ends up covering the element. When I hold the device horizontally, the tooltip adjusts its position accordingly. I attempted to apply custom CSS to the too ...

Having difficulties showing live data in real-time, the Python web application is encountering an "Internal Server Error" while attempting to do so

The application is receiving real-time data (verified by using an alert), but when trying to display it on the card, an Internal Server Error occurs. The same code runs fine as an independent HTML page but not in a Flask Python web app. <!DOCTYPE ...

Picked (chosen-js): Steps to deselect options using a variety of selectors

I am currently using the Chosen library on Vue and Webpack for my project. I have a scenario where I need to cancel a selection when multiple options are selected, but I am struggling to achieve this. Can anyone guide me on how to cancel a selected optio ...

Obtain a range of dates within a specified timeframe by utilizing JavaScript

Is there a way in JavaScript to retrieve a list of days between two dates in MySQL format without using any libraries? Here is an example of how it can be done: function generateDateList(from, to) { var getDate = function(date) { //MySQL Format ...

Having trouble retrieving features from a QR code generated with Angularx-qrcode?

I utilized angularx-qrcode in order to create a QR code that displays data from qrInfo. However, I'm encountering the following error: ERROR TypeError: Cannot read properties of undefined (reading 'qrcElement') The code within qr-code-gener ...

Manage thrown errors using http.post().subscribe()

There is a backend API for logging in with the possibility of returning a 401 Unauthorized error if the password provided is incorrect. I am wondering how to effectively manage and handle exceptions raised in Angular when interacting with this API. this.h ...

Steps to create a clickable button wrapper label in React

Contained within the components below: <CheckboxGroupLabel htmlFor={option.label}> <FormCheckbox onClick={() => onChange} key={option.label} defaultChecked={defaultChecked} {...rest} /> {option.value} ...

The functionality of Inettuts within JavaScript seems to malfunction whenever I attempt to reposition the div

I developed a widget framework using inettuts and integrated database functionalities with ajax in asp.net and sqlserver. Widgets are dynamically loaded based on user data from the database, but I encountered an issue when trying to move a widget - the J ...

Error Encountered in Request Header of WordPress JSON API

Utilizing the WordPress JSON API plugin has allowed me to effectively retrieve posts and other content from my blog. However, an issue arises when attempting to access the data from my Ionic application. The following error occurs: Request header field A ...

Is there a way to utilize an Event Emitter to invoke a function that produces a result, and pause until the answer is provided before continuing?

Looking for a way to emit an event from a child component that triggers a function in the parent component, but with a need to wait for a response before continuing. Child @Output() callParentFunction = new EventEmitter<any>(); ... this.callParen ...

Utilize mui-tiptap to effortlessly upload images to your content

My current project involves using the mui-tiptap module in React 18 with Vite. Specifically, I am facing an issue with uploading a local image to my backend. The problem seems to lie in my frontend code, as I am encountering a TypeScript error that is prev ...

What is the best way to update information in a mongoose document using the _id field?

Although it may sound like a typical question, I've already conducted research and couldn't find a solution. I'm currently working on developing a discord bot and I don't have much experience in this area. The issue I keep encountering ...

Using JavaScript to extract the metadata of an image from a remote location

Is there a way to extract XMP metadata from a JPEG file using JavaScript? I came across a method for doing it in PHP (How can I read XMP data from a JPG with PHP?) which can be adapted for JavaScript using AJAX. However, the issue arises when trying to acc ...

Retrieve data from jQuery and send it to PHP multiple times

<input type="checkbox" value="<?= $servicii_content[$j]['title'] ?>" name="check_list" id="check" /> By using jQuery, I am able to extract multiple values from the table above once the checkboxes are checked. Here's how: var te ...

Nuxt2 is not compatible with the current Long-Term Support version of Node (v18)

As a newcomer, I am embarking on my first Vue.js project with Nuxt. After executing "npm run dev" in the command prompt and running "npm install" for my project, I encountered the following: * Client ██████████████████ ...

Tips for structuring JSON data to retrieve numerous values

Creating a tool where users can enter their postcode to check for nearby windfarms is my current project. I have organized the data by named locations, and it's important to maintain that structure due to the specific API mapping tool I am using. Here ...

Exploring Cypress: Iterating over a collection of elements

I have a small code snippet that retrieves an array of checkboxes or checkbox labels using cy.get in my Angular application. When looping through the array to click on each element and check the checkboxes, it works fine if the array contains only one elem ...

What is the process for defining the type of the context for an Apollo resolver?

I am facing an issue with my Apollo GraphQL subgraph where I need to define the type for the context argument in my resolvers. When creating a resolver, I tried setting the context type like this: interface Context { dataSources: { shopify: Shopify; ...

Tips for managing the response from a POST request using jQuery

I'm currently working on sending data via POST to my ASP.Net MVC Web API controller and retrieving it in the response. Below is the script I have for the post: $('#recordUser').click(function () { $.ajax({ type: 'POST', ...

Incorporating AngularJS and Bootstrap for seamless pagination experience

My JSON data looks like this: http://localhost:3001/images?page=1 {"images":[{"_id":"542e57a709d2d60000c93953","name":"image1","url":"http://www.syll.com","__v":0},{"_id":"542e58e19d237e5b790f4db2","name":"image154","url":"www.rufyge.com"},{"_id" ...