Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
848 views
in Technique[技术] by (71.8m points)

javascript - Vue.js watching deep properties

I'm trying to watch properties on a vue.js object, but i'm not getting the result that i want, my code is the following:

var vueTable = new Vue({
    el: '#vue-table',
    data: {
        filters: {},
    },
    watch: {
        filters: {
            handler: function () {
                console.log('watched');
            },
            deep: true
        }
    }
}

And i have a v-model on an input like so:

<input class="form-control" v-model="filters.name">

Now when the page loads it logs watched in the console just once, whenever i change the input it doesn't log anything.

Yet when i put vueTable.filters = {name: 'something'}; after the table initalization it will trigger on every change.

Is this unexpected behaviour? or do we have to define all our properties in order for them to be watched?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The documentation covers this here.

Due to the limitations of modern JavaScript (and the abandonment of Object.observe), Vue cannot detect property addition or deletion.

By starting with an empty object and setting v-model to filters.name, you end up adding a property dynamically. The best approach in this case would be to initialize the property in the data. It doesn't have to have a value.

data: {
    filters: { name: null },
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...