Watching a specific property amongst various objects using VueJS deep watcher

Issue at Hand

In my scenario, I have an array named "products" that consists of multiple objects. Each object within the product array includes a property called "price". My goal is to monitor any changes in this particular property for each product. This monitoring is necessary to calculate a commission price whenever a user modifies the price in an input field.

This is how my products array is structured;

[
  0: {
    name: ...,
    price: ...,
    commission: ...,
  },
  1: {
    name: ...,
    price: ...,
    commission: ...,
  },
  2: {
    name: ...,
    price: ...,
    commission: ...,
  },
  ...
  ...
  ...
]

Implemented Code

I coded the following solution, which unfortunately only captures the initial load of products and not subsequent changes;

    watch  : {
        // Watch for changes in the product price, in order to calculate final price with commission
        'products.price': {
            handler: function (after, before) {
                console.log('The price changed!');
            },
            deep   : true
        }
    },

The products get loaded using this method;

mounted: async function () {
            this.products = await this.apiRequest('event/1/products').then(function (products) {
                // Attach reactive properties 'delete' & 'chosen' to all products so these can be toggled in real time
                for (let product of products) {
                    console.log(product.absorb);
                    Vue.set(product, 'delete', false);
                    Vue.set(product, 'chosen', product.absorb);
                }

                console.log(products);

                return products;
            })
        }

Additional Resources Referenced Vue.js watching deep properties This question revolves around observing a property that is not yet available. VueJs watching deep changes in object In this case, the focus is on monitoring changes in a different component.

Answer №1

To truly understand the inner workings of products.price, it's important to recognize that price belongs to an individual product, not the products array as a whole.

When dealing with declarative watchers and arrays, complications can arise when trying to reference specific indexes in the watch expression, such as products[0].price, which may trigger a warning from Vue.

[Vue warn]: Failed watching path: “products[0].price”. Watcher only accepts simple dot-delimited paths. For more control, consider using a function instead.

This suggests that utilizing a programmatic watch with a function might be a more effective approach, albeit with limited documentation on the topic.

If you find yourself in a similar situation, one possible solution is outlined below:

<script>
export default {
  name: "Products",
  data() {
    return {
      products: []
    };
  },
  mounted: async function() {
    this.products = await this.apiRequest('event/1/products')...

    console.log("After assigning to this.products", this.products);

    // Implement watchers here, utilizing a common handler
    this.products.forEach(p => this.$watch(() => p.price, this.onPriceChanged) );

    // Simulate a change
    setTimeout(() => {
      console.log("Changing price");
      this.products[0].price= 100;
    }, 1000);
  },
  methods: {
    onPriceChanged(after, before) {
      console.log(before, after);
    }
  }
};
</script>

For further exploration, a test environment like Codesandbox (where color is used instead of price for demonstration purposes) can provide valuable insights.

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

Using ngFor in Angular 2-5 without the need for a div container wrapping

Using ngFor in a div to display an object containing HTML from an array collection. However, I want the object with the HTML node (HTMLElement) to be displayed without being wrapped in a div as specified by the ngFor Directive. Below is my HTML code snipp ...

Encountering an issue while fetching information from a JSON file using JavaScript

I am encountering an Uncaught SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data let mydata = JSON.parse("file.json"); console.log(myJSON) Here is a sample of the JSON file's data: [[1,1,0,1,1,0,0,0,1,1,1,1,1, ...

Issue with bouncing dropdown menu

I am in the process of enhancing a Wordpress website by implementing a jQuery menu with sub-menus. Below is the jQuery code snippet: $(document).ready(function(){ $('.menu > li').hover(function(){ var position = $(this).position(); ...

What could be the reason for the malfunctioning of my express delete request?

When I send a delete request using Postman on my localhost, everything functions correctly. However, when trying to make the same request from my React.js client-side, it doesn't go through. Below is the API request: router.delete("/deletetransaction ...

What is the best way to create an array containing dictionaries?

Hey there, I'm having an issue with my React.js code. Here's what I have: const array1 = [1, 4]; const map1 = array1.map(x =>{'x2': x * 2, 'x3': x * 3}); console.log(map1); // expected output: Array [{'x2': , 1, ...

React error message: "Cannot update state on a component that is not mounted" unless using the useEffect hook

(I am a beginner using Next.js + Styled Components and need help :)) I'm currently working on creating a "Netflix" style page, with unique catalog components. Each content item in the grid is a complex component named ContentItem.js that is repeated ...

Angular not displaying retrieved data

Having an issue with fetching data from an API using Angular. Although the console log confirms that the data is successfully fetched, it doesn't display on the page. Any assistance would be greatly appreciated. Take a look at my code: app.component. ...

Require assistance with understanding the aes-256-cbc encryption using oaepHash

Procedure for Secure Data Encryption: Generate a random 256-bit encryption key (K_s). For each Personally Identifiable Information (PII) value in the payload: 1. Pad the plaintext with PKCS#7 padding. 2. Create a random 128-bit Initialization Vector (IV). ...

Converting an Ajax request from JavaScript to jQuery

I am new to Ajax and trying to convert an ajax request from javascript to jquery without success. Here is the javascript code snippet I am working with: function aaa(track_id) { var req = new XMLHttpRequest(); req.open("get", "list.php?tr=" + track_id, ...

ERROR: The value property is undefined and cannot be read in a ReactJS component

Can someone help me with the error I'm encountering in the handleChange function? I'm not sure what the issue could be. const [testState, setTestState] = useState({ activeStep:0, firstName: '', lastName: '&apos ...

Is it the right time to implement a JavaScript framework?

Is there a need for using JavaScript frameworks like Angular or React if you are not developing single-page websites or components that receive live updates? ...

Error message in Node v12: "The defined module is not properly exported."

When trying to export a function in my index.js file, I encountered an error while running node index.js: module.exports = { ^ ReferenceError: module is not defined Is there a different method for exporting in Node version 12? ...

Ensuring the accurate promise is delivered in Angular

I'm struggling to correctly return the promise for a service in Angular. Here is the function causing me trouble: postToSP.post($scope.sharePointURL, data).then(function() { $scope.gettingData = false; $scope.yammerListName = ...

Can a function be embedded within a React render method that includes a conditional statement to update the state using setState()?

My application randomly selects three values from an array found within defaultProps and then displays these values inside div elements in the return JSX. It also assigns these values to properties in the state object. I am facing a challenge where I need ...

The MongoClient object does not possess the 'open' method

I recently started working on a project using Node.js, Express.js, and MongoDB. I've encountered some issues while trying to set up the database configuration. Below is a snippet of code from my index.js file: var http = require('http'), ...

The code in check.js causes a square of dots to emerge on the screen in Skype

Trying to add a Skype call button to my page has been successful, but there's one issue - a pesky white dot keeps appearing at the bottom of the footer. The script source I used is as follows: <script src="http://download.skype.com/share/skypebu ...

Is it possible to merge a variable within single quotes in XPath?

Currently working with nodeJS and experimenting with the following code snippet: for (let i = 1; i <= elSize; i++) { try { let DeviceName = await driver .findElement(By.xpath("//span[@class='a-size-medium a-color-base a-text-normal ...

The Datetimepicker component outputs the date in datetime format rather than a timestamp

Currently, I am utilizing the datetimepicker JavaScript script with specific implemented logic: <script> var today = new Date(); var dd = today.getDate(); var mm = today.getMonth(); var yy = today.getF ...

The robot will automatically update its own message after a designated period of time

I am facing an issue with my code where the bot is not updating its message after a specific time period defined by time.milliseconds * 1000. How can I make the bot edit its message after that duration? let timeout = 15000; if (author !== null && ...

When clicking on the side-bar, it does not respond as expected

My website has a menu layout that features a logo on the left and an icon for the menu on the right side. When the icon is clicked, the menu slides in from the right side of the window, and when clicked again, it slides out. However, I am facing two issues ...