What is the correct way to refresh a prop when being utilized as the starting value?

I'm trying to figure out the most efficient way to handle a situation where I need to mutate a list of items within a component that accepts this list as a prop. To address this, I referred to the VueJs documentation and set the initial value of a data property to be the same as the prop value, so that I could make changes to the data property when needed.

export default {
  props: {
    items: {
        type: Array,
        default: () => {
            return []
        }
    }
  },
  data() {
    return {
        itemList: this.items
    }
  }
}

However, I noticed that the itemList property remains stuck at the initial value and doesn't update if the parent component provides a new value for items. This is because the component has already been rendered and does not re-evaluate its data properties. To address this issue, I added a watcher to monitor any changes in items:

watch: {
   items() {
        this.itemList = this.items;
    }
}

I came across this other question which had a similar problem and used the same solution that I implemented. However, I am curious to know if this method is considered reliable and standard practice, or if there are alternative approaches to resolve this issue?

Answer №1

The data attribute utilizes the property solely for initial setup. It remains unaffected by any subsequent changes in the property value.

On the other hand, a computed attribute will react to such changes. Although another approach exists, setting up a watcher with a function that modifies the data attribute seems more appropriate if no actual computation is involved with the property value.

However, a basic watcher only scratches the surface. The suggested method may not work as intended if the parent element alters the array by adding or removing elements. It should only respond when the entire array is reassigned by the parent element.

In case you require the watcher to also monitor mutations in the property, considering implementing a deep watcher:

watch: {
   items: {
    handler(newValue) {
      this.itemList = JSON.parse(JSON.stringify(newValue)); //creates a deep copy of the array to prevent any modifications by child components from affecting the parent's array. Keep in mind that this technique has its limitations.
    },
    deep: true
  }
}

However, this approach can be resource-intensive when dealing with a large array prop.

Moreover, it appears that you intend for your component's state ($data.itemList) to be altered simultaneously by both the component itself and its parent. This scenario could lead to complications like racing conditions, so caution is advised.

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

Processing of hierarchical JSON structure

I have a JSON array that I am trying to duplicate only once while keeping it unique. Here is the code I have attempted: return_data = {}; return_data.planner = [{ "date": "2019-08-30T12:10:08.000Z", "event": [{ "name": "Event 1", "col ...

Error: The function $.get is not recognized when using jQuery with babel-node

Currently, I am executing the code below from a test.js file using babel-node in the command line: babel-node test.js installation of jquery npm i --save jquery test.js: import $ from 'jquery'; $.get("www.google.com"); Upon execution, I en ...

How should we provide the search query and options when using fuse.js in an Angular application?

Having previously utilized fuse.js in a JavaScript project, I am now navigating the world of Angular. Despite installing the necessary module for fuse.js, I'm encountering difficulties implementing its search functionality within an Angular environmen ...

excessive memory usage in a simple react-native application

My experience with creating my first react native app has been more challenging than I initially expected. I'm having trouble understanding what I might be doing wrong. Initially, the app is simple, fetching data through Redux. componentWillMount() ...

Why does this particular user continue to encounter validation errors in ASP.NET?

While most of us successfully submitted the request form for server decommission, one particular individual encountered an issue. They were unable to submit the form due to a pop-up alert stating "Invalid User Data, return to form." Despite verifying their ...

Update the text using JavaScript to modify the price range dropdown when the user clicks away

Dropdown functionality is working when selecting a price, but updating the price in the text box manually does not trigger an update. How can you implement an onblur change event for manual entry of prices? JSFiddle function nFormatter(num, digits) { ...

Store the output of the function in a variable

Here is a script that was provided to me: <div id="container1"> <script> var script = document.createElement("script"); script.type = "text/javascript"; script.text = 'document.write(xmlDoc.getElementsByTagName("INFO") ...

Generate a new perspective by incorporating two distinct arrays

I have two arrays containing class information. The first array includes classId and className: classes = [ {classid : 1 , classname:"class1"},{classid : 2 , classname:"class2"},{classid : 3 , classname:"class3"}] The secon ...

Sorting through an array using several filter arrays

Is there a way to efficiently filter an array of items based on multiple filter arrays? Each item has various filters, and I want to display only the ones that match all selected filters. const selectedFilters = { color: ["Red", "Blue"], type: ["S ...

Numerous ajax requests

I am utilizing a for-loop to make multiple ajax requests: for(var o = 1; o <= 2; o++) { $.ajax({ type: 'GET', url: 'lib/terrain.php', ...

Unending scroll marquee in Vue JS (horizontal bar)

I am seeking advice on how to create an infinite loop marquee using Vue Js and jQuery in my project. The current project Fiddle can be found here: https://jsfiddle.net/jackbauer/xz5wv617/7 The current implementation successfully displays a crypto currency ...

Conquering cross-origin resource sharing (CORS) using XMLHttpRequest without relying on JSONP

Appreciate your time in reading this inquiry! For the past few days, I've been grappling with an AJAX request issue. Despite scouring through numerous answers on Stack Overflow, I'm still unable to find a resolution. Any assistance would be grea ...

What is the best way to add hidden columns in Telerik Grid MVC3?

I'm currently working with a grid where I need to hide certain columns using the following code: foreach (var attr in grid.Attr) .Columns(columns => { columns.Bound(attr.key) .Width(attr.width) .Visible(attr.isVisi ...

What is the best way to retrieve a file's creation date using the file System module in Node.js

I'm having trouble fetching the filename and file creation date to send to a client. I tried using fs.stat which provides birthtime but does not include the filename. So, my question is: is birthtime equivalent to the file created date? How can I sen ...

What is the best way to save the response data into an array outside of the current function in Node.js?

How can I efficiently store all the result data into an array called pImages? I am able to retrieve the results, but I believe using an async function would be more suitable. However, I am unsure of how to implement it. Any assistance would be greatly appr ...

Javascript puzzle - I have 99 obstacles

...but a malfunction isn't one. Hey there, I am new to learning so I apologize for the seemingly simple question. I'm experimenting with a theoretical logic statement that would work using javascript. For instance: if (issues == 99) { malfunct ...

What is the best way to trigger a flash animation on the front end?

CODE: login.ejs <script> req.flash('success_msg', 'You have logged in'); </script> header.ejs <div class = "alertMessage"> <% if (success_msg != false){ %> <span class="alert alert-success ...

Adjusting elements within nested JavaScript arrays

When using the code below, an empty array containing 7 empty arrays is expected to be created, essentially forming a 7x7 grid. While accessing elements within nested arrays seems to work correctly, attempting to modify their values causes all elements in ...

Encountered an issue while executing the npm run dev command in a React project

Hello, I am a beginner with React.js and I am currently trying to set up a simple React application locally using webpack. However, when I run the npm run dev command, I encounter the following error: An error occurs in the command prompt after running np ...

Building a JSON-powered navigation bar with Bootstrap 4

Looking to create a custom navigation bar using Bootstrap 4 and populate it with items from a JSON file. Despite researching various methods, there seems to be limited resources available on this topic. Any assistance or guidance would be greatly appreciat ...