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

前端 未结 3 995
迷失自我
迷失自我 2020-12-16 11:18

My data object:

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

My template:


                        
    
提交评论

  • 2020-12-16 11:55

    I think you can do this:

    watch: {
        $data: {
            handler: function(val, oldVal) {
                console.log(val)
            },
            deep: true
        }
    },
    
    0 讨论(0)
  • 2020-12-16 12:03
    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)
    }
    
    0 讨论(0)
  • 提交回复
    热议问题