vue watch深度监听数组每一项的变化
    		       		warning:
    		            这篇文章距离上次修改已过450天,其中的内容可能已经有所变动。
    		        
        		                
                在Vue中,你可以使用watch来深度监听一个数组的每个元素的变化。为了实现这一点,你需要为数组中的每个元素设置一个单独的观察者。这里有一个简单的例子:
<template>
  <div>
    <div v-for="(item, index) in myArray" :key="index">
      <input v-model="item.propertyToWatch">
    </div>
  </div>
</template>
 
<script>
export default {
  data() {
    return {
      myArray: [
        { propertyToWatch: 'Item 1' },
        { propertyToWatch: 'Item 2' },
        { propertyToWatch: 'Item 3' }
      ]
    };
  },
  watch: {
    myArray: {
      handler: function(newVal, oldVal) {
        // 当数组变化时触发
        console.log('Array changed:', newVal);
      },
      deep: true
    }
  },
  created() {
    // 为数组中的每个对象设置深度观察者
    this.myArray.forEach((item, index) => {
      this.$watch(`myArray[${index}].propertyToWatch`, (newVal, oldVal) => {
        console.log(`Item ${index} changed from ${oldVal} to ${newVal}`);
      });
    });
  }
};
</script>在这个例子中,myArray是一个包含对象的数组。我们在组件创建后(created钩子中)遍历数组,并为每个对象的propertyToWatch属性设置一个单独的深度观察者。当任何propertyToWatch的值发生变化时,都会触发对应的函数,并输出相关信息。同时,也设置了一个普通的watch监听整个数组的变化。
评论已关闭