Observing the timepiece malfunctioning beyond expectations

Let me explain the issue here in a simple way. I have a parent component where I execute a method that changes a property value of an object called products. This is working fine.

However, when I pass this object as a prop to a child component and watch it deeply, it fails. You can see that the alert('changed'); is never triggered:

Vue.component('child', {
props: ['prods'],
  watch: {
  prods: {
    handler: function(new_val, old_val) {
      alert('watched');
      },
      deep: true
    }
  }
})

new Vue({
  el: '#app',
  template: '<div>{{products[0].value}}<br><button v-on:click="incre">increment prod 0</button></div>',
  data: {
  products: [
    {id: 1, name: 'prod1', value: 20},
      {id: 2, name: 'prod2', value: 40},
    ],
  },
  methods: {
    incre: function() {
      this.products[0].value += 20;
    }
  }
})
<script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3345465673011d071d07">[email protected]</a>/dist/vue.js"></script>
<div id="app">
  <child v-bind:prods="products"></child>
</div>
https://jsfiddle.net/dmbgmxzh/6/

(Update):
this works: https://jsfiddle.net/dmbgmxzh/5/
this doesn't: https://jsfiddle.net/dmbgmxzh/6/
This is strange...

Answer №1

Another approach could be to send the product as a prop to the child component and watch each product separately. Here's an example:

Vue.component('child', {
    props: ['product'],
    watch: {
        product: {
            handler: function (new_val, old_val) {
                alert('watched');
            },
            deep: true
        }
    }
})
new Vue({
    el: '#app',
    data: {
        products: [
            {
                id: 1,
                name: 'prod1',
                value: 20
            },
            {
                id: 2,
                name: 'prod2',
                value: 40
            },
    ],
    },
    methods: {
        incre: function () {
            this.products[0].value += 20;
        }
    }
})
<script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f0868595b0c2dec4dec4">[email protected]</a>/dist/vue.js"></script>
<div id="app">
    <div>{{products[0].value}}<br><button v-on:click="incre">increment prod 0</button></div>
    <child :product="product" v-for="product in products"></child>
</div>

For more information, refer to this post.

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

A tiny blue spot popping up beside the roster of users

I'm working on a render function that displays a list of users with avatars and names. The issue I'm facing is that when the page initially loads, there's a blue dot to the left of each user. However, if I navigate to another page and then g ...

How to retrieve an element using a dynamically generated class name in Vue.js

<v-data-table :headers="menuheaders" //this menus from api response :items="menus" item-key="usersmenu_menuid" items-per-page="1000" hide-default-footer="" class="elevation-1" > <template v-s ...

Is it possible to extract information from a form's POST request without relying on the traditional "action" attribute within form elements?

Last night, I was experimenting with ExpressJS and discovered something interesting when working with a simple code snippet: app.post('/contact', function(req, res, next) { res.send('Congratulations! You have submitted the form'); }) ...

What is the best way to access an external array using ng-repeat in AngularJS?

My dataset consists of 3 separate arrays. "areas": { "default": [ { "area": "Master Bedroom", "uuid": "986e3f42-1797-49ae-b060-181a33b9", "description": "", "new": [ { "value": "986e3f42-1797-49ae-b060-181a3 ...

Alter the dimensions and material displayed on Vue

In my Vue.js project, I have a topbar with two divs whose size and content need to be adjusted based on whether the user is logged in. If they are not logged in, it should look like this: <div id='search' width="400px"></div><div ...

Tips for extracting the src attribute from a dynamically generated iframe

My dilemma stems from a function that generates an iframe with content on my website, which unfortunately I cannot control as it is loaded remotely. The function initially creates: <span id="myspan"></span> Once the JavaScript function fu ...

Clear all CSS styles applied to a targeted division

My website built on Wordpress links to several CSS files. One specific div has its own unique style that is separate from the main Wordpress styles. Unfortunately, the Wordpress CSS ends up interfering with my custom div's layout. Is there a way in HT ...

Is it possible to use v-if when dealing with data that is loaded after computation

I am facing a challenge where I need to hide a component based on data that is loaded in the mounted lifecycle hook. However, it seems that using v-if with computed properties only is causing an issue because the data is not ready yet (since computed is ca ...

Are you familiar with the Pagination and Card Components offered by Ant Design (antd)?

Can you merge the Pagination feature from antd with Card components to create a layout resembling Pinterest, complete with pagination? The standard Pagination code from https://ant.design/components/pagination/: import { Pagination } from 'antd&apo ...

Issue with JQuery mobile: dynamically inserted popup fails to appear

Can you help me troubleshoot an issue with my function? It's supposed to take a text string and output the text surrounded by '¬¬¬' in a button with a pop-up menu attached. The button looks fine, but when clicked, the popup ul list doesn& ...

Storing an array of objects in Firestore using JavaScript presents a challenge

I am attempting to save an object to Firestore which includes an array: { returnMode: false, id: "SE-74c5219a-acfe-4185-9e33-f78b10ac3f1e", prices: [ { price: { twoHours: 0, firstHour: 0, id: "zero&quo ...

How can one effectively handle elements or objects that are both event listeners and event triggers?

Yesterday, I posted a similar question but found it too complex and vague after further research, so I removed it. I have now created a new demo here, which should be self-explanatory for the most part. Below are the HTML and JavaScript sections: <sel ...

Issue found within triggered hook: "TypeError: Unable to retrieve property '$http' as it is undefined"

Hey there, I've created a userInfo() function to fetch user data and utilize it in different areas. How can I effectively call this function to retrieve the necessary information? Can anyone assist me with this issue? export function getUserInfo () { ...

Issues with form rendering in a Vue.js component

I have recently started learning vue.js and I'm trying to create a basic form using the materializecss framework within a component. The form requires this jQuery snippet to function: $(document).ready(function() { M.updateTextFields(); }); ...

Unable to click on link with JavaScript using Selenium webdriver

<a id="compareCompanies" b:onclick="needsController.showQuotes = true;" href="#">Compare companies</a> Below is the Selenium Webdriver JavaScript code using Mocha: driver.wait(function () { driver.findElement(webdriver.By.id("compareCompa ...

How can you reset a variable counter while inside a forEach loop?

I am currently working on resetting a counter that is part of a recursive forEach loop within my code. Essentially, the code snippet provided calculates the length of the innermost key-value pair as follows: length = (key length) + (some strings inserted) ...

Combining and arranging numerous items in a precise location in three.js

I am currently working on a web application using three.js with Angular and facing some challenges when trying to set the precise positions of objects. The requirement is to load various objects and position them in specific locations. In order to load di ...

Passing role data from Django Rest Framework and Djoser to the Vue frontend

I'm currently developing a basic website with a login feature. I am utilizing the Djoser library to handle authentication on the backend, and have successfully implemented the login functionality. Now, I want to create restricted access pages on the f ...

Difficulty encountered when attempting to utilize keyup functionality on input-groups that are added dynamically

I've exhausted all available questions on this topic and attempted every solution, but my keyup function remains unresponsive. $(document).ready(function() { $(document).on('keyup', '.pollOption', function() { var empty = ...

Divide a nested list into individual lists

I am working on a navigation menu with nested lists and I need to split the nested lists using jQuery while keeping the original headings intact. Can anyone help me achieve this? Below is the HTML code: <ul id="bigList"> <li><a href="#"& ...