我在试着理解如何正确地观察一些道具的变化。 我有一个父组件(。Vue文件),从ajax调用接收数据,把数据放在一个对象中,并使用它来通过v-for指令渲染一些子组件,下面是我的实现的简化:

<template>
  <div>
    <player v-for="(item, key, index) in players"
      :item="item"
      :index="index"
      :key="key"">
    </player>
  </div>
</template>

... 然后在<script>标签内:

 data(){
     return {
         players: {}
 },
 created(){
        let self = this;
        this.$http.get('../serv/config/player.php').then((response) => {
            let pls = response.body;
            for (let p in pls) {
                self.$set(self.players, p, pls[p]);
            }
    });
}

Item对象是这样的:

item:{
   prop: value,
   someOtherProp: {
       nestedProp: nestedValue,
       myArray: [{type: "a", num: 1},{type: "b" num: 6} ...]
    },
}

现在,在我的孩子“播放器”组件中,我试图观察任何项目的属性变化,我使用:

...
watch:{
    'item.someOtherProp'(newVal){
        //to work with changes in "myArray"
    },
    'item.prop'(newVal){
        //to work with changes in prop
    }
}

这是可行的,但对我来说似乎有点棘手,我想知道这是否是正确的方法。我的目标是每次道具改变或myArray获得新元素或现有元素中的一些变化时执行一些操作。任何建议都将不胜感激。


当前回答

我个人更喜欢这种简洁的实现方式:

watch: {
  myVariable: {
     handler(newVal, oldVal){  // here having access to the new and old value
     // do stuff
       console.log(newVal, oldVal);
     },
     deep: true,
     /*
         Also very important the immediate in case you need it,
         the callback will be called immediately after the start
         of the observation
     */
     immediate: true 

  }
}

其他回答

对于任何寻找Vue 3的人


import { watch } from 'vue';

...
...

watch(
  () => yourNestedObject,              // first param, your object
  (currValue, prevValue) => {          // second param, watcher callback
    console.log(currValue, prevValue);
  },
  { deep: true }                       // third param, for deep checking
);

您可以在这里参考文档:https://v3.vuejs.org/guide/reactivity-computed-watchers.html#watch

你可以使用深层观察者:

watch: {
  item: {
     handler(val){
       // do stuff
     },
     deep: true
  }
}

现在它将检测对项目数组中对象的任何更改以及对数组本身的添加(当与Vue.set一起使用时)。这是一个JSFiddle: http://jsfiddle.net/je2rw3rs/

EDIT

如果你不想观察顶层对象的每一个变化,只是想要一个不那么尴尬的语法来直接观察嵌套对象,你可以简单地观察一个computed:

var vm = new Vue({
  el: '#app',
  computed: {
    foo() {
      return this.item.foo;
    }
  },
  watch: {
    foo() {
      console.log('Foo Changed!');
    }
  },
  data: {
    item: {
      foo: 'foo'
    }
  }
})

这是JSFiddle: http://jsfiddle.net/oa07r5fw/

另一种更好的方法是:

 watch:{
     'item.someOtherProp': function (newVal, oldVal){
         //to work with changes in someOtherProp
     },
     'item.prop': function(newVal, oldVal){
         //to work with changes in prop
     }
 }

(我从评论里的@peerbolte那里学到了这个方法)

如果你想看一段时间的财产,然后取消它怎么办? 或者查看库子组件属性?

你可以使用“动态观察者”:

this.$watch(
 'object.property', //what you want to watch
 (newVal, oldVal) => {
    //execute your code here
 }
)

$watch返回一个unwatch函数,如果被调用,它将停止监视。

var unwatch = vm.$watch('a', cb)
// later, teardown the watcher
unwatch()

你也可以使用deep选项:

this.$watch(
'someObject', () => {
    //execute your code here
},
{ deep: true }
)

请一定要看一下医生

我使用了deep:true,但发现在监视函数中的新旧值始终是相同的。作为之前解决方案的替代方案,我尝试了这个,它将通过将整个对象转换为字符串来检查它的任何变化:

created() {
    this.$watch(
        () => JSON.stringify(this.object),
            (newValue, oldValue) => {
                //do your stuff                
            }
    );
},