Vue: Can I $watch whole $data but except some properties?

Created on 14 Jul 2014  路  8Comments  路  Source: vuejs/vue

See the code here:

new Vue({
    el: '#x',
    data: {
        prop1 : '',
        prop2 : '',
        ...
        result : ''
    },
    ready: function(){
        this.$watch('$data', function(){
            this.load(function( xx ){
                // # This will cause '$data change' again, then do 'load' again, infinity looping...
                this.result = xx;
                // /
                // So, can I watch the whole $data but except the 'result'?
            });
        });
    },
    methods: {
        load: function( callback ){
            var self = this;
            doSomeAsync(function( xx ){
                callback.call(self, xx);
            });
        }
    }
});

Did I use it in the right way?

Most helpful comment

All 8 comments

Or if I could know which property get changed in the $data, the problem can be solved too.

There are a few ways. You can just make the properties a separate object and watch that...

new Vue({
    el: '#x',
    data: {
        properties: {
            prop1 : '',
            prop2 : '',
            ...
        }
        result : ''
    },
    ready: function(){
        this.$watch('properties', function(){
    }

... or, as the documentation says, "Additional properties attached to the ViewModel or the data object in the ready hook will not be observed." , so you can introduce this.result="" there.

Alternatively, again as the docs say, when it comes to processing object in $data, "Properties with keys that starts with $ or _ are skipped." , so you can just rename to "$result" or "_result".

Thank you @bdaglish, but I made some test, the result is still not what I want:

Way 1: Use a wrapper scope for not watching "result", can solve my problem, but I feel it's not so good..
Way 2: I try a demo, but I saw property that attached in the ready hook was still being observed.
Way 3: Use "_result" can truly make it not be observed, but "_result" dosen't render in HTML template, demo here.

Interesting use case - I can make some improvements to the $watch interface so that the event includes the exact path that changed inside the object, but that has to wait till the next major release...

Im the meanwhile, grouping them into different objects seems to be the easiest workaround.

Okay, I'm using the "grouping" way to fit my case, and looking forward to "$watch" new feature. : )

I closed it too fast, the "grouping" way make my code be fatter...
And should it be an 'enhancement' tag?

@asip , the key problem: addcalculate is an async function in my case.

Was this page helpful?
0 / 5 - 0 ratings