A child component in Vue.js unexpectedly starts updating when the parent component renders and uses object literals as props

I'm currently facing an issue with my Vue components where object literals are passed as props like:

<child :prop1="{ foo: 'bar' }"></child>

After rerendering the parent component, the prop prop1 changes and triggers an update in the Child component. However, if the prop is an object reference, it remains unchanged.

Why does this behavior occur and does it imply that using object literals (and possibly array literals) as props may not be reliable?

https://codesandbox.io/s/vue-template-jj0tb

Answer №1

Every time the template is executed, a new object is created when it reaches that section. The same concept applies to any reference type, such as arrays, functions, and more.

Similar to objects created in JavaScript code, each call to a function like getObject will result in a new object being returned.

function getObject() {
    return {};
}

console.log(getObject() === getObject()); // false

When using objects in JavaScript, the equality is based on reference rather than the values contained in the objects. Vue utilizes a similar approach when checking for changed props, as Vue templates are compiled down to a render function which is essentially plain JavaScript with object literals remaining as they are.

In the scenario mentioned, the render function for the parent component would generate a new object for prop1 each time it runs, assuming the template only includes the parent-child relationship:

function render(h) {
    return h('child', {
        props: {
            prop1: {foo: 'bar'}
        }
    })
}

To avoid unnecessary child updates, it is recommended to store the object in the data section and reference it by name to ensure the same object is utilized consistently.

The significance of this practice depends on the specific scenario, as extensive child updates can potentially impact performance. While child rendering typically doesn't require updating the DOM directly, computed properties, watches, or templates reliant on that prop may run if modified.

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

Nuxt3 encountered a request error for an unhandled 500 fetch failure at the http://localhost:3000/__nuxt_vite_node__/manifest url

Can you help me understand this error? https://i.stack.imgur.com/0FGa4.png Without making any adjustments to my code, the app builds successfully. However, when running it on dev mode, the following error appears: npm run dev I have attempted rebuilding ...

Combining Django, Graphene, Apollo, django-webpack-loader, and Vue: Struggling with CORS and CSRF compatibility issues?

Currently, I am immersed in a project that involves Django as the backend, Vue as the frontend, and Apollo/Graphene/GraphQL as the data transfer layer. While most of it is functioning smoothly, I am encountering difficulties with the CORS/CSRF settings. I ...

The error message "firebase.initializeApp is not defined" indicates that the object is not properly initialized

Every time I try to open the debugger in Safari, I encounter an error indicating that 'undefined' is not recognized as an object when evaluating 'firebase.initializeApp'. The error specifically points to the line of code: firebase.initi ...

Guide to concealing List elements from the Search Filter when the search input field is emptied

I am facing a challenge with an HTML list of items. Here is the structure: <ul id="fruits"> <li><a href="#">Mango</a></li> <li><a href="#">Apple</a></li> <li><a href="#">Grape</a>& ...

Error thrown in JavaScript when calculating the distance

I am currently working on calculating distances between two points, but I keep getting an error that says Uncaught TypeError: a.lat is not a function. function MapLocations() { var i = 0; var infoWindow = new google.map ...

Tips for associating an id with PrimeNg menu command

Within my table, I have a list of items that I would like to enhance using PrimeNg Menu for dropdown menu options. The goal is to enable navigation to other pages based on the selected item id. When a user clicks on a menu item, I want to bind the id of th ...

Is it possible to swap out one ID value for another using JavaScript?

I am facing two issues 1) First Issue I need to update the current id value with a new one. Whenever the a tag is clicked, an event in jQuery code should be triggered to change the id value. For example, When a button is clicked <div class="video" i ...

What about numerical inputs lacking spinners?

Is there a more efficient way for users to input a decimal number like 64.32, and have it be two-way-bound to a property of type number? I attempted to use <input type="number" [(ngModel)]="size"> However, this displays a spinner which isn't ...

Firebase will automatically log users out after one hour of inactivity

After conducting thorough research, I have learned that Firebase updates a refresh token every hour because Firebase ID tokens expire after one hour. It is mentioned that the automatic refreshing of tokens by Firebase occurs without any action required fro ...

javascript: window.open()

I am currently using VB.NET 2005 and I have a requirement to launch a new browser window using Process.Start(). The challenge is that I need to specify the size of the browser window, for example, height:300 and width:500. Process.Start("firefox.exe", "ab ...

What could be the reason for my dynamic image not appearing in a child component when using server-side rendering in Nuxt and Quasar

Currently, I am tackling SSR projects using Nuxt and Quasar. However, I encountered an issue when trying to display a dynamic image in a child component as the image is not being shown. The snippet of my code in question is as follows: function getUrl (im ...

The splash screen fails to show up when I launch my Next.js progressive web app on iOS devices

Whenever I try to launch my app, the splash screen doesn't show up properly. Instead, I only see a white screen. I attempted to fix this issue by modifying the Next Metadata object multiple times and rebuilding the PWA app with no success. appleWebApp ...

How to initiate focus on Angular 2 MdInputContainer after the view has been

I am encountering an issue with setting focus on the first md-input-container element within a component when the view loads. Despite implementing a @ViewChild property and calling focus on it in the ngAfterViewInit method, the focus does not seem to be wo ...

JavaScript animation for sequencing traffic lights

I have been working on completing a task that was assigned to me. (iii) Explain the organization of an array that could manage the traffic light sequence. (iv) Develop a script that utilizes the array outlined in part (iii) to create an animated display ...

Error: The import declaration is clashing with the local declaration of 'defineProps' in Vue version 3.3

Today, I encountered several errors after updating my node_modules and Vue to v3.3. The project utilizes Vue 3.3, WebPack (not Vite), and VS Code Volar. It is a large project. In every file with *.vue containing <script setup lang="ts">, ...

Using Vue.js to bind labels and radio buttons in a form

My goal is to generate a dynamic list of form polls based on the data. However, using :for or v-bind:for does not result in any HTML markup appearing in the browser, causing the labels to not select the corresponding input when clicked. I have prepared a J ...

Acquire an array of Worksheet names in JavaScript by utilizing ActiveX

How can I retrieve a comprehensive list of all available sheet names from my Excel file using the ActiveX Object? I am aware that the code Excel.ActiveWorkBook.Sheets provides access to the sheets. However, how do I obtain an array containing the NAMES of ...

Is there a way to distribute my World instance among several step definition files in CucumberJS?

Currently, I am working on implementing a CucumberJS scenario that involves using multiple steps spread out across two separate step definition files. In this setup, the first step establishes certain variables in the World object which need to be accessed ...

Transfer the selected user content from one canvas to another

After successfully implementing a simple selection area on canvasA, I encountered an issue with copying the area to canvasB. The user is supposed to select an area and then see that selection appear on another canvas once they finish making the selection b ...

Using v-for to show the values of an object in Vuetify

I am currently developing a function in vuejs that allows users to select tables from a database, with the columns' names automatically appearing in a v-list-item component. However, I am facing difficulty in displaying these column names effectively. ...