Observing nested objects in Vue while utilizing deep watching功能

Is there a way to determine which property change in the object triggered the watch call while watching a data object with multiple properties using deep invocation?

data(){
   return {
        user:{
           first_name:'',
           last_name:'',
            }
    }
},
watch:{
    user:{
       deep:true,
       handler(value){
       //I need to know which specific property (first_name/last_name) within the user object triggered this watch call.
        }
    }
}

Answer №1

Here is an example of how you can achieve this:

<template>
  <div>
    <div>
      <input type="text" v-model="obj.prop1" />
      <input type="text" v-model="obj.prop2" />
      <input type="text" v-model="obj.prop3" />
    </div>
  </div>
</template>

<script>
export default {
  name: 'app',
  data: () => ({
    obj: {
      prop1: '',
      prop2: '',
      prop3: '',
    },
  }),
  mounted() {
    for (const key in this.obj) {
      this.$watch(
        () => this.obj[key],
        (newValue, oldValue) => {
          console.log(key, oldValue, newValue);
        }
      );
    }
  },
};
</script>

By using the this.$watch method, you can set up dynamic watchers.

For more information, please refer to the documentation: https://v2.vuejs.org/v2/api/#watch

Answer №2

Vue seems to lack a method for pinpointing which property has changed.

Using the example provided triggers the watch callback whenever any property changes.

However, Vue does offer another option:

// keypath
vm.$watch('a.b.c', function (newVal, oldVal) {
  // perform some action
})

https://v2.vuejs.org/v2/api/#vm-watch

In your scenario, it might look something like this:

data(){
   return {
        user:{
           first_name:'',
           last_name:'',
            }
    }
},
watch:{
    "user.first_name": function(newVal, oldVal) {
      // do something
    },
    "user.last_name": function(newVal, oldVal) {
      // do something
    }
}

Although I'm unsure if this is the most effective approach

Update from Vue documentation

Note: when mutating (instead of replacing) an Object or an Array, the old value will be the same as the new value because they point to the same Object/Array. Vue doesn't store a copy of the pre-mutate value.

Manually comparing objects in this case is futile since newVal = oldVal (same reference)

Update 2: Creating a new object may serve as a workaround

// for instance
user = Object.assign({}, user, { first_name: "newValOfFirstName" })

// instead of
user.first_name = "newValOfFirstName";

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

Styling pagination using CSS and jQuery

I am looking to display 3 sections in a simple, paginated way that mimics tabs. I am trying to implement the logic where when a pagination item is clicked and has the 'active' class, it should show the corresponding block. However, I am strugglin ...

Unspecified tag name attribute in Vue that can be accessed in the browser

At the moment, I have encountered an issue with a selector in Vue returning undefined for {{ lens.price }}. However, when I use a = lens[1].getAttribute('price') in the browser console, it correctly displays the value as "0". Why is Vue showing ...

Why is my HTTP request callback not being executed?

I've been trying to send an HTTP POST request to a 3rd-party API using a promise method. Oddly enough, the callback function never seems to run, even though when I test the code on its own, the API call is successful. Node.js and the concept of an e ...

Can the ES2016 Proxy be used to intercept the "typeof" operation?

Can a handler property be defined to intercept typeof proxyObject? It is not mentioned in any of the traps listed on Mozilla. ...

three.js canvas, sphere rotates gracefully to the right

Trying to get the sphere to turn right at a very slow pace. Here is my source code: I have created a new container with canvas inside, you can view the code below. How can I make the sphere turn slowly? You can also check out my git repository on github: s ...

You cannot call this expression. The type 'String' does not have any call signatures. Error ts(2349)

Here is the User class I am working with: class User { private _email: string; public get email(): string { return this._email; } public set email(value: string) { this._email = value; } ...

Testing for the presence of a child element within a parent component in React

Below is the structure of my component: const Parent = (props) => { return <div>{props.children}</div>; }; const Child1 = (props) => { return <h2>child 1</h2>; }; const Child2 = (props) => { return <h2>child 2 ...

What causes the failure of $event binding when using RowGroup tables with PrimeNG?

I have successfully implemented RowGroup to store 3 different tables, which is working great. However, I am facing an issue with the onRowSelect function not functioning properly. When I click on any row of the RowGroup tables, nothing happens. On another ...

Engaging User Forms for Enhanced Interactivity

I'm in the process of developing an application that involves filling out multiple forms in a sequential chain. Do you have any suggestions for creating a more efficient wizard or form system, aside from using bootstrap modals like I currently am? C ...

Is it necessary to include my library dependencies in the devDependencies section if I am only planning to publish the library bundle?

When creating a bundle for a library, should the library dependencies be placed in devDependencies? I am developing an NPM library in TypeScript that relies on several dependencies, including React components. As part of the build process, we compile to J ...

Bizarre Angular directive nesting issue discovered after upgrading from version 1.4.9 to 1.5.0

Forgive the unclear title; I am still trying to pinpoint exactly what is causing issues after the upgrade. Could it be a problem with nested directives or template inconsistencies? (see sample images & links to CodePens below) Issue I have a basic o ...

Manipulate jQuery to set the table row containing empty table data cells to be lower than the row with

I am using HTML and jQuery to sort my table, including non-standard sorting with multi-tbody. The issue I am facing is that the prices (Цена) in the td are sorted ascending but not correctly. Why is this happening? Additionally, I need to move the tr&a ...

What is the process of invoking a JavaScript function from Selenium?

How can I trigger a JavaScript function from Selenium WebDriver when using Firefox? Whenever I am logged into my website, I typically utilize this command in Firebug's Command Editor to launch a file upload application: infoPanel.applicationManager. ...

Encountering the error 'Cannot read property 'length' of undefined' while attempting to fetch data from a URL using node.js

While attempting to create a Discord-Bot capable of looking up definitions on urbandictionary, I encountered an error after trying to fetch the json from their api. const args = Array.prototype.slice.call(commandArgs); if (!args.length) { return m ...

Creating an interactive map on WordPress: A step-by-step guide

I have successfully created a clickable image on Codepen <div style="width: 1000px; height: 993.73px;"> <img src="https://www.dyfedarchaeology.org.uk/wp/wp-content/uploads/Testmap.svg" alt=&q ...

Retrieving a Date object from a JSON response

Hey there, I have a situation where I'm trying to convert a JSON response into a date object in order to display it in a different format. Here's the JSON response I'm working with: responseData: [{"id":10,"createdDate":"1 Sep, 2014 12:48:5 ...

My content is being obstructed by a single-page navigation system

I attempted to create a simplified version of the issue I am facing. Basically, I am working on a header with navigation that stays at the top of the page while scrolling. The problem arises when clicking on a section in the navigation. The screen scrolls ...

Guide to setting up Gatsby CLI and Gatsby version 2

Currently, I am working on a project that utilizes Gatsby v2 in its package.json file. However, to run the project, I need to globally install Gatsby-cli as per the documentation. Strangely, the global installation of Gatsby-cli also installs Gatsby v4, ca ...

What is the best way to divide this string with jQuery?

Is there a way to use jQuery to split this specific string? "[10.072721346470422,76.32974624633789][[10.075854059674523,76.32043361663818],[10.073650930297095,76.32888793945312],[10.074918540288232,76.33090496063231],[10.073862198974942,76.33137702941895] ...

Nuxt sends a POST request to Laravel Sanctum which ultimately redirects to the login page

I have spent countless hours debugging and searching online with no success. My setup includes Laravel 8 with the Sanctum package, along with the latest Nuxt version as the front-end. I have successfully implemented GET requests on a couple of endpoints. H ...