Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
209 views
in Technique[技术] by (71.8m points)

vue watch问题

请问一下,如下代码中当changeData执行后,未触发watch,是为什么?ps:使用注释的那段代码是能够监听到的。

export default {
  name: 'App',
  setup() {
    const stateRef = reactive<any>({
      data: {},
    });
    
    // const stateRef = reactive<any>({
    // data: {a:0},
    // });

    const changeData = () => {
      stateRef.data.a = Math.random();
    };

    watch(
      () => stateRef,
      () => {
        console.log(stateRef.data.a);
      },
      {
        deep: true,
      },
    );

    return {
      changeData,
    };
  },
}

下面方法也不行,是为什么呢?

export default {
  name: 'App',
  setup() {
    const stateRef = reactive<any>({
      data: {},
    });
    stateRef.data.a = 0; // 新增此行
    
    const changeData = () => {
      stateRef.data.a = Math.random();
    };

    watch(
      () => stateRef,
      () => {
        console.log(stateRef.data.a);
      },
      {
        deep: true,
      },
    );

    return {
      changeData,
    };
  },
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

经过一番搜索找到了答案,官方文档

1、实例化的时候,不存在的属性不是响应式的:
image.png

2、参考setup文档

从生命周期钩子的视角来看,setup 会在 beforeCreate 钩子之前被调用。

再查看beforeCreate文档

实例初始化之后,数据观测 (data observer) 和 event/watcher 事件配置之前被调用。

因此,setup执行时,响应式属性已经确定,所以之后添加的属性不是响应式的。


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...