请稍等 ...
×

采纳答案成功!

向帮助你的同学说点啥吧!感谢那些助人为乐的人

关于Vue3的watch的问题

我在练习watch的时候发现了一个小问题,老师看一下这个例子

export default {
  name: "App",
  setup() {
    let state = reactive({
      name: "Mr.Jack",
      age: 18,
      info:{
        city:"Beijing"
      }
    });
    function changeData(){
      state.info.city = "shanghai";
    }
    watch(state,(newVal,oldVal)=>{
      console.log("数据发生了变化")
      console.log(newVal);
      console.log(oldVal);
    })
    return {
      state,
      changeData
    };
  },
};

在这个例子中,监听state,默认会开启deep,也就是修改state.info.city会触发watch
但是在下面这个例子中,我监听state.info,如果不配置deep就不会触发watch,为什么呢?

    watch(()=>state.info,(newVal,oldVal)=>{
      console.log("数据发生了变化")
      console.log(newVal);
      console.log(oldVal);
    },{deep:true}) //这里必须要开启deep配置不然就失灵了

所以就是,为什么监听state不用开deep,监听state.info就必须开启deep呢?这两者都是proxy对象呀

正在回答 回答被采纳积分+3

1回答

双越 2021-12-18 23:04:48

你把 watch(state, ...) 改为 watch(() => state, ...) 试试。按照文档里的写法,应该用函数

https://v3.cn.vuejs.org/guide/reactivity-computed-watchers.html#%E4%BE%A6%E5%90%AC%E5%8D%95%E4%B8%AA%E6%95%B0%E6%8D%AE%E6%BA%90 

0 回复 有任何疑惑可以回复我~
  • 提问者 JhinKoo #1
    确实,正规写法应该都写成函数。我只是很好奇为什么会出现这个机制,
    回复 有任何疑惑可以回复我~ 2021-12-19 12:34:53
  • 双越 回复 提问者 JhinKoo #2
    这个我也没研究过,因为一直是按照他文档的方式写的。
    回复 有任何疑惑可以回复我~ 2021-12-19 15:42:58
问题已解决,确定采纳
还有疑问,暂不采纳
意见反馈 帮助中心 APP下载
官方微信