The prop observation was activated without any alterations

Within my component, I have a prop X that I assign to data Y during the created hook. This setup allows me to easily modify Y without affecting X. Both X and Y are Arrays.

Additionally, I've set up a watch on prop X to ensure Y is updated whenever X changes.

However, I've noticed that my watch statement is being triggered every time I use methods like Y.sort().

Here's a simplified version of the code:

props: {
    X: Array
},
data: function() {
    return {
        Y: []
    }
},
methods: {
    someFunc() {
        this.Y.sort() // Triggers the watch on X
    }
},
watch: {
    X (newVal) {
        this.Y = newVal;
    }
},
created: function() {
    this.Y = this.X;
}

Why is this happening?

I've thoroughly examined my app from all angles, but there doesn't seem to be anything in the template or other methods that would update the parent prop.

Answer №1

When you assign this.Y = this.X;, any changes made to Y will directly affect X as well. To prevent this, consider one of the following solutions:

 this.Y = this.X.slice();

or

Object.assign(this.Y,this.X)

Here's a JavaScript example illustrating this concept:

let a = [44, 23, 16, 5, 52, 36]
console.log(a) //print the original a
let b = a;

b.sort((c, d) => {
  return c - d
});

console.log(a) //a is sorted however we do not call a.sort(...) method

Answer №2

Most array functions do not alter the original array.

An exception is sort ;)

Due to sort rearranging the items in your array, the watcher gets triggered.

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

Encountering "npm WARN optional dep failed, proceeding with fsevents" error while attempting to install vue-cli on AWS/EC2 instance

I'm in the process of setting up vue-cli on AWS. Everything seems good with my permissions, and I have node v4.4.5 installed. Upon executing npm install --global vue-cli, the cursor flashes for approximately 30 seconds before displaying this error m ...

I am encountering an issue where req.body is returning as undefined

After creating a controller with the code below: app.post('/users', (req, res) => { console.log(req.body); const user = new User({ name: req.body.name, email: req.body.email }); user.sa ...

Exploring the utility of promise.race()

When it comes to promise, there are two main options that I am aware of: promise.all() promise.race() I have a good grasp on what promise.all() does. It runs promises simultaneously, and upon successful resolution, the .then method provides you wit ...

Accessing form objects in Typescript with AngularJS

I am currently working with AngularJS and Typescript. I have encountered an issue while trying to access the form object. Here is the HTML snippet: <form name="myForm" novalidate> <label>First Name</label> <input type="text" ...

Preload-webpack-plugin does not support pre-fetching files

I have a query about prefetching and preloading content. In my vue app, I noticed that after building, I have duplicate files loaded in my dist/index.html file. Here is an example: Additionally, the "scripts" are not being preloaded/prefetched as expec ...

Unable to modify attribute within $templateCache through an AngularJS Directive

Here is my Directive code: module.directive('iconSwitcher', function() { return { restrict : 'A', link : function(scope, elem, attrs) { var currentState = true; elem.on('click', function() { ...

Enable the use of empty spaces in ag-grid filter bars

I'm experiencing an issue with the ag grid filter. It seems to be disregarding white spaces. Is there a way to configure the grid to recognize blank spaces in the filter? Any suggestions for resolving this issue? Where can I find the option to accept ...

Unable to execute AJAX POST request

https://i.stack.imgur.com/JqG7c.pngI have a JSON dataset like the one below: [ { "Password": "tedd", "Username": "john", "status": true } ] I need to consume this data using a POST method <label for="Username">Username:</label& ...

Divinely favored - pay attention for each and every sound

Currently, I am utilizing node with the blessed tty library downloaded from NPM. Within this library, there is a method called "key" that I am using in the following way: blessed.key(['q', 'z'], function(ch, key) { //do something ...

Anonymous self-executing functions with parameters from an external scope

Recently, I stumbled upon the code snippet below while following a tutorial. const increment = (function(){ return function incrementbytwo (number){ return number+2; } })(); console.log(increment(1)); The result of the code above is 3. ...

The "events" module could not be resolved in React-Native

The server encountered an internal error: 500 URL: Body: {"message":"There was an issue resolving the module events from the specified directory. This may be due to a module not existing in the module map or directories listed.","name":"UnableToResolveEr ...

When inputting forms into the database, identifiers are used instead of names. Despite this, the user interface functions without any issues

In this demonstration, I am building a dynamic conditional drop-down list using Java script and Ajax. PHP: Add Data <html> <head> <title>Add Data</title> </head> <body> <?php //including the database connection ...

Different ways to enhance max-http-header-size in Vue application

After being redirected from another application, I am unable to open the page and receive an error in the console: Failed to load resource: the server responded with a status of 431 (Request Header Fields Too Large). I came across information about max-h ...

Guide on utilizing the list of names in a POST request

<td class="widht200"> <input type="text" name="agg" size="2" disabled="disabled"/> </td><td class="widht200"> <input type="text" name="agg" size="2" disabled="disabled"/></td><td class="widht200"> <input type=" ...

Tips for validating a form's input on an ajax page with the help of jQuery

I am facing an issue with a form containing two inputs. The first input can be validated before triggering an ajax function, but the second input cannot be validated. The second input is loaded from a page using ajax, along with the submit button. I need t ...

Executing an SQL delete query with a button click using a JavaScript function in PHP

I have created a setup with three essential files - index.html, database.php, and function.js. In database.php, there is a form generated containing a delete button that triggers the deletion SQL query when clicked. The primary objective is to present a ta ...

Why does the Element.style.left property keep rejecting my input value?

I have encountered a problem with the positioning of elements, specifically with the 'left' property. I've designed a rectangular block using CSS and rotated it by 0.17 radians in JavaScript. Now, my aim is to make the block move diagonally ...

"Retrieve the most recent information without refreshing the page by employing the Vue script setup along with Axios after submitting data

Looking for assistance as I am new to working with vue.js. I currently have 2 Vue files that serve different purposes: Greetinglist.vue, which retrieves data from an API using axios.get Greeting.vue, responsible for posting data using axios.post Upon su ...

Generate a collection of div elements as child nodes

I'm working on a project where I have multiple rows with input fields. My goal is to create an array for each row that contains the values of the inputs. For example, if I have 3 rows and the values of 'input1' are 1, 'input2' are ...

Randomly injecting strings like 'jQuery111201xxx' into a string using jQuery Ajax

After implementing a booking system that utilizes FullCalendar, I encountered an unusual issue with the 'notes' field. Occasionally, a strange string is inserted into the notes field at random points. Here's an example of what I found recent ...