vue3.0自定义hook中watch不执行

匿名用户
  • 217

Test1 Component:

import { watch } from "@vue/composition-api";
import useFoo from "../hooks/useFoo.js";

export default {
  name: "HelloWorld",
  props: ["count1"],
  setup(props) {
    watch(() => {
      //will print when props.count1 changed
      console.log("Test1 Count1", props.count1);
    });
    const { foo } = useFoo(props.count1);
    return {
      foo
    };
  }
};

useFoo hook:

import { watch, ref } from "@vue/composition-api";

export default function(count1) {
  const foo = ref(2);
  watch(() => {
    //will not print when props.count1 changed
    console.log("useFoo count1", count1);
  });
  return {
    foo
  };
}

我想复用一些逻辑,但是发现hook中watch不起作用【console.log("Test1 Count1", props.count1);为何没有执行】?
DMOE: https://codesandbox.io/s/head...

回复
阅读 1.4k
1 个回答
✓ 已被采纳
setup(props: any) {
    watch(() => {
      console.log(props.someData, '1')
    })
}

先说一下这里为什么不执行

因为setup的参数props是只读的,无法赋值自然执行不了watch

先看一下源码:
image.png

readonly被包装了set方法,LOCKEDfalse才可以赋值

image.png

所以如果要赋值可以这样写:

const observed: any = readonly({ a: 1 })
let dummy
// watch 在 effect 基础进行了封装
effect(() => {
    dummy = observed.a
})
unlock()
observed.a = 2
lock()
// observed.a = 2
// dummy = 2
你知道吗?

宣传栏