如何在Vue 2中观察数据对象中的所有键

27

我的数据对象:

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

我的模板:

<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>
我怎样能同时观察到两个选定的索引?我希望每当任意一个索引更新时都能做类似这样的事情:
watch: {
    selected: function(o, n) {
        ...
    }
}

3
如果您只想观察所有数据,请添加一个'$data'的观察。 - KyleMit
3个回答

33
您可以使用vue的watcher提供的deep选项。如文档所述:
“要检测对象内部的嵌套值更改,您需要在options参数中传递deep:true。请注意,您不需要这样做来监听数组突变。”
代码示例如下:
watch: {
    'selected': {
        handler: function (val, oldVal) {
            console.log('watch 1', 'newval: ', val, '   oldVal:', oldVal)
        },
        deep: true
    }
}

30

我认为你可以做到这一点:

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

8
我认为这个答案提供了一个新的角度。简洁而优美。 :) - Eerik Sven Puudist
2
@匿名 - 他的回答不仅很好,而且完全不是多余的:它显示了可以观察内置的data对象,这是其他回答没有展示的。 - Dan
1
不知道有 deep: true 这个功能,非常好用!同时,在解构参数对象时非常干净,比如说使用 ES6 中的 handler: function({ value1, value2 })。我唯一担心的是它会监视 $data 中的所有内容。有没有人知道如何只监视解构后的参数?单独编写监听器就不够 DRY。 - Justin La France
我认为这是您正在寻找的内容:https://dev59.com/J1gQ5IYBdhLWcg3w1njm - user7153178

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

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

如果你只是想从selected计算出一个新的数据,你可以使用计算属性(computed properties),因为Vue的数据是响应式的,计算属性也可以检测到数据的变化。


如果你想使用单个函数来观察整个对象,你可以使用带有deep: true$watch

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

请注意,'$data.selected'是一个字符串,Vue会对其进行解析。

在你的方法中:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接