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


2023年4月09日 21:58:01   2,764 次浏览

方式一

在Vue中,我们可以使用watch选项来监听数据的变化。下面是一种监听$store.state.userInfo.Name的变化的方式:

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);
  }
}

 

#区别

::: info 区别一:第二种方式是先通过计算属性时刻监测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);
  }
}

 

发表评论

邮箱地址不会被公开。 必填项已用*标注