Vue监听store中数据变化的两种方式

方式一

watch: {
    
    
  "$store.state.userInfo.Name":{
    
    
    handler:function(newVal,oldVal){
    
    
      console.log(newVal,oldVal);
    }
  }
}

方式二

computed: {
    
    
  isEdit () {
    
    
    return this.$store.state.userInfo.Name;  //需要监听的数据
  }
},
watch: {
    
    
  isEdit(newVal, oldVal) {
    
    
    console.log(newVal,oldVal);
  }
},

区别

  • 区别一:第二种方式是先通过计算属性时刻监测store的数据变化,从而触发isEdit的监听函数,明显需要多一步
  • 区别二:如果监听store的数据是一个对象,第一种方式只需要加上深度监听,也可以实现数据的变化监听,而第二种方式却无法监听到store的对象数据变化,例如

第一种方式

watch: {
    
    
  //此时我监听的是对象,当$store.state.userInfo.Name发生修改时,此时需要深度监听才能监听到数据变化
  "$store.state.userInfo":{
    
    
    deep:true,//深度监听设置为 true
    handler:function(newVal,oldVal){
    
    
      console.log("数据发生变化啦"); //修改数据时,能看到输出结果
      console.log(newVal,oldVal);
    }
  }
}

第二种方式

computed: {
    
    
  isEdit () {
    
    
    return this.$store.state.userInfo;  //需要监听的数据
  },
},
watch: {
    
    
  isEdit(newVal, oldVal) {
    
    
    console.log("数据发生变化啦"); //修改数据时,看不到该输出结果,因为无法监听到数据的变化
    console.log(newVal,oldVal);
  }
},

猜你喜欢

转载自blog.csdn.net/weixin_42000816/article/details/110948868