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
652 views
in Technique[技术] by (71.8m points)

vuejs2 - How do I watch all keys in a data object in Vue 2

My data object:

data: {
    selected: {
        'type': null,
        'instrument': null
    },

My template:

<select v-model="selected['instrument']" @change="switchFilter('instrument', $event)">
    <option v-for="instrument in instruments" :value="instrument.value">@{{ instrument.text }}</option> 
</select>

<select v-model="selected['type']" @change="switchFilter('type', $event)">
    <option v-for="type in types" :value="type.value">@{{ type.text }}</option> 
</select>

How can I watch both selected indexes at the same time? I want to do something like this everytime any of the indexes updates:

watch: {
    selected: function(o, n) {
        ...
    }
}
See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

You can use deep option provided by the watcher from vue. As stated in the docs:

To also detect nested value changes inside Objects, you need to pass in deep: true in the options argument. Note that you don’t need to do so to listen for Array mutations.

You code will look like following:

watch: {
    'selected': {
        handler: function (val, oldVal) {
            console.log('watch 1', 'newval: ', val, '   oldVal:', oldVal)
        },
        deep: true
    }
}

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

...