Vue JS Watching deep nested object

前端 未结 4 1937
深忆病人
深忆病人 2021-02-04 23:47

Disclaimer: This is my first attempt at building an MVVM app I have also not worked with vue.js before, so it could well be that my issue is a result of a more

相关标签:
4条回答
  • 2021-02-05 00:16

    You could use the 'watch' method.. for example if your data is:

    data: {
        block: {
            checkbox: {
                active:false
            },
            someotherprop: {
                changeme: 0
            }
        }
    }
    

    You could do something like this:

    data: {...},
    watch: {
       'block.checkbox.active': function() {
            // checkbox active state has changed
            this.block.someotherprop.changeme = 5;
        } 
    }
    
    0 讨论(0)
  • 2021-02-05 00:22

    If you want to watch the object as a whole with all its properties, and not only just one property, you can do this instead:

     data() {
        return {
           object: {
              prop1: "a",
              prop2: "b",
           }    
        }
     },
     watch: {
        object: {
            handler(newVal, oldVal) {
                // do something with the object
            },
            deep: true,
        },
    },
    

    notice handler and deep: true

    0 讨论(0)
  • 2021-02-05 00:29

    Since nobody replied and I have solved/ worked around the issue by now, I thought it migth be useful to post my solution. Please note that I am not sure my solution is how these types of things should be tackled, it works though.

    Instead of using this event listener v-on="change: checkboxChange(this)" I am now using a custom directive which listens to both the selected and disabled model attribute, like this: v-on-filter-change="selected, disabled".

    The directive looks like this:

    directives: {
        'on-filter-change': function(newVal, oldVal) {
            // When the input elements are first rendered, the on-filter-change directive is called as well, 
            // but I only want stuff to happen when a user does someting, so I return when there is no valid old value
            if (typeof oldVal === 'undefined') {
                return false;
            }
            // Do stuff here
            // this.vm is a handy attribute that contains some vue instance information as well as the current object
            // this.expression is another useful attribute with which you can assess which event has taken place
        }
    },
    

    The if clause seems a bit hacky, but I couldn't find another way. At least it all works.

    Perhaps this will be useful to someone in the future.

    0 讨论(0)
  • 2021-02-05 00:41

    Other solution not mentioned here: Use the deep option.

    watch:{
      block: {
        handler: function () {console.log("changed") },
        deep: true
      }
    }
    
    0 讨论(0)
提交回复
热议问题