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

≯℡__Kan透↙ 提交于 2019-12-19 05:14:05

问题


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) {
        ...
    }
}

回答1:


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
    }
}



回答2:


I think you can do this:

watch: {
    $data: {
        handler: function(val, oldVal) {
            console.log(val)
        },
        deep: true
    }
},



回答3:


watch: {
  'selected.type': function (newSelectedType) {
    console.log(newSelectedType)
  },

  'selected.instrument': function (newSelectedinstrument) {
    console.log(newSelectedinstrument)
  }
}

If you are just trying to calculate a new data from selected, you can just use computed properties, since the data of Vue are reactive, the computed properties can also detect the changes of data.


If you want to use a single function to watch 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 parse it.

and in your methods:

onSelectedUpdate (newSelected) {
  console.log(newSelected)
}


来源:https://stackoverflow.com/questions/41626565/how-do-i-watch-all-keys-in-a-data-object-in-vue-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!