Disregard certain attributes when implementing a deep watch in VueJs

I'm currently developing an automatic save feature for a Vue application that sends data to an API every time there is a change in the data. I am wondering if it is possible to selectively ignore certain properties of an object when using a Vue watch. The object contains multiple values that I want to monitor for auto-saving, but there are 1 or 2 properties that I would like to exclude. Instead of setting up individual watch functions for all the properties I want to track, I'd prefer to just ignore the ones that don't need to be watched.

Here is the basic structure of the data:

data:{
  template: {
    name: "Template",
    id: 1,
    variables: [
      {
        name: "v1",
        color: "#fff",
        group: 1,
        isSelected: true
      },
      {
        name: "v2",
        color: "#fff",
        group: 3,
        isSelected: false
      }
    ]
  }
}

And here is the simplified watch function:

watch: {
  template: {
    handler: function(){
      this.save();
    },
    deep: true
  }
}

The 'isSelected' field within the 'variables' in the template is used solely for UI purposes and should not trigger the watch function as these changes are not saved. Rather than creating a specific watch function for each field in 'variables', I would like to include something in the watch like:

ignore: "template.variables.isSelected"

Answer №1

To address the issue of not being able to retrieve the old value for a mutation object, one possible solution is to create auxiliary data for storing the old values. By creating a temporary variable such as temp(save old data), you can effectively compare old and new data to tackle the problem.

var app = new Vue({
el: "#app",
data:{
  a: 1,
  template: {
    name: "Template",
    id: 1,
    variables: [
      {
        name: "v1",
        color: "#fff",
        group: 1,
        isSelected: true
      },
      {
        name: "v2",
        color: "#fff",
        group: 3,
        isSelected: false
      }
    ]
  },
  temp: {}
},
mounted: function() {
// this.template.variables[0].isSelected = false;
 this.temp = JSON.parse(JSON.stringify(this.template));
 this.$set(this.template.variables[0],"isSelected", 222);
 
},
watch : {
 template: {
   handler: function(changeVal) {
     var flag = true;
     for(var i in changeVal.variables) {
       if(changeVal.variables[i].isSelected != this.temp.variables[i].isSelected) {
         flag = false;
       }
     }
     this.temp = JSON.parse(JSON.stringify(this.template)); // assign changed data as old data again for next process
     if(flag) console.log("saveData");// this.save();
     else console.log("notsave");
   },
   deep: true
 }
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app"></div>

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 is the proper way to utilize the data inherited from my parent component?

As a newcomer to VueJS, I am in the process of setting up a simple website that allows users to customize certain elements, such as the background image. Users can upload an image from the admin section of the website, which will then be used as the backg ...

When utilizing getServerSideProps, the data is provided without triggering a re-render

Although my approach may not align with SSR, my goal is to render all products when a user visits /products. This works perfectly using a simple products.map(...). I also have a category filter set up where clicking on a checkbox routes to /products?catego ...

Leveraging the power of animate.css library to enhance page transitions on Nuxt

I've been working on implementing the animate.css library for nuxt page transitions, but I'm encountering some issues. I have successfully added animate.css to the nuxt.config.js file and it loads without any problems. However, when I try to use ...

An attempt to access the login API at http://localhost:3000 resulted in an Internal Server Error with a status

I encountered an issue in the console stating: "POST http://localhost:3000/api/login 500 (Internal Server Error)". It seems like there is a problem reaching the API during the login process: Below is my login component written in React: import React, { us ...

difficulty updating data values with $emit on a Vue object

Utilizing $emit to facilitate communication between a child and parent component. A method in the child component triggers the $emit at different stages of an api call. For instance, before initiating the api call, certain values need to be sent to the par ...

Create a duplicate <li> element and animate it using jQuery

Here are the list items: <ul> <li>...</li> <li>...</li> <li>...</li> <li>...</li> <li>...</li> <li>...</li> <li>...</li> <li>...</li> <li>...</l ...

Once the ajax jQuery is triggered, I hope to see an image loading for a brief moment of just 1

Can someone assist me with the following code snippet? <script type="text/javascript"> $(function () { $(".a").live("click", function () { var $this = $(this), ProductImageId = $this.data('ProductImageId'); ...

Using Javascript to create session-specific cookies

Is it possible to create session-only cookies using JavaScript that get removed when the browser is closed? Due to limitations, the website I am working on is HTML-only, so server-side scripts cannot be utilized. I came across a method mentioned here: b ...

The REST API endpoint links for Timestamp are displaying a 404 error message indicating they cannot be

After recently diving into backend development, I ran some tests locally using Postman and localhost which seemed to work perfectly. However, upon uploading my code to GitHub, I encountered a 404 error when clicking on the API endpoint hyperlinks from inde ...

JavaScript encounters an error when trying to create a MarkLogic instance with an array

[javascript] XDMP-CAST: (err:FORG0001) xs:string#1(.) -- Invalid cast: `json:object(<json:object xmlns:xs="http://www.w3.org/2001/XMLSchema" ` xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" .../>) cast as xs:string Stack Tr ...

The success function is not being executed when using the jQuery .ajax call

Here is the jQuery code snippet for calling a JSON web service: function fetchMajorGroups(){ var element = $(".item-group-button"); var response = $.ajax({ type:"GET", url:"http://localhost:6458/posApplication/touch/getAllMajorGro ...

Adjust the size of the text editor in eXtplorer's EditArea module

Looking for guidance on adjusting the height of the text editor (EditArea) within eXtplorer. Any assistance would be greatly appreciated! ...

how to properly position an image using javascript

I have two tilesheet images and I have successfully rendered them, but I am struggling to figure out how to place the character in front of the map. https://i.stack.imgur.com/n1a3Q.png I have placed these images in two different JavaScript files. This i ...

Unusual occurrences when using absolute positioning, style.top, style.left, and the HTML "a" tag

Struggling to complete a task on Javascript.info involving an "a" tag. The objective is simple - place (and remove) a tooltip above the element upon hover. No issues with positioning over the roof or house, but as soon as I try to place the box a ...

Issue encountered during Nuxt installation: A rule can only contain one resource source, which consists of the provided resource and the test + include + exclude

After successfully installing Vue.js and Node.js, I encountered an issue while trying to install Nuxt.js. Here is the error message that I received. Despite asking for help from friends, the problem still persists. Any assistance would be greatly appreciat ...

What is the best way to dynamically change the color of a Vue component button through a function?

Can anyone provide guidance on how to change the button color of a Vue component using a function while utilizing Bootstrap-vue? The code snippet below demonstrates how a tooltip can be altered through a function, but how can this concept be extended to mo ...

I keep encountering a network error whenever I try to refresh the page. What could be causing this issue? (

Whenever I make a GET request to an API using useEffect(), everything works fine when I navigate from the homepage to the page. However, if I refresh the page at http://localhost:3000/coins/coin, I encounter an error message saying "Unhandled Runtime Error ...

Recursively mirroring the contents of a webpage following the execution of JavaScript code

My goal is to recursively mirror a webpage, meaning I want to retrieve all pages within that webpage. Since all the webpages are located in subfolders of one main folder, I thought I could easily accomplish this using wget: wget --mirror --recursive --pag ...

Is there a way for me to invoke a different function that is located external to

I am currently in the process of setting up an event that triggers on any change within the form input class. import React, { useState } from "react"; DealerRegistration extends React.Component { state = { business_type : 'd ...

Tips for invoking a JavaScript class method from an HTML document

I've created a Typescript class that dynamically inserts an HTML element to a page after it's loaded. Here is the code snippet: const calcElement: string = ` <div class="container"> <span class="cc-title">Field</span> ...