How to view 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 similar every time I update indexes:

 watch: { selected: function(o, n) { ... } } 
+5
source share
2 answers

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

To also detect changes in nested values ​​inside objects, you need to go in depth: true in the options argument. Note that you do not need to do this to listen for Array mutations.

The code will look like this:

 watch: { 'selected': { handler: function (val, oldVal) { console.log('watch 1', 'newval: ', val, ' oldVal:', oldVal) }, deep: true } } 
+11
source
 watch: { 'selected.type': function (newSelectedType) { console.log(newSelectedType) }, 'selected.instrument': function (newSelectedinstrument) { console.log(newSelectedinstrument) } } 

If you are just trying to compute new data from selected , you can simply use the calculated properties, since Vue data is reactive, the calculated values ​​can also determine data changes.


If you want to use one function to view the entire object, you can use $watch with deep: true :

 mounted () { this.$watch('$data.selected', this.onSelectedUpdate, { deep: true }) } 

note that '$data.selected' is a string, Vue will '$data.selected' it.

and in your methods:

 onSelectedUpdate (newSelected) { console.log(newSelected) } 
+3
source

Source: https://habr.com/ru/post/1262714/


All Articles