Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

watch特性 #14

Open
geekact opened this issue May 6, 2022 · 2 comments
Open

watch特性 #14

geekact opened this issue May 6, 2022 · 2 comments
Labels
help wanted Extra attention is needed

Comments

@geekact
Copy link
Member

geekact commented May 6, 2022

自从computed特性上线后并不断完善后,watch特性也在准备了。

computed和watch的不同点在于触发方式,computed是用的时候才计算,属于被动式,而watch是一旦依赖变化就要及时地主动触发。

目前有以下几种方案:

defineModel('test', {
  watch: {

    // 方案一:自动收集依赖,缺点是为了收集依赖,第一次必须执行
    test1() {
      document.title =  this.state.x.y.z;
    },

    // 方案二:手动收集依赖,缺点是修改业务的时候容易漏掉,而且字符串没有提示容易写错,增加了心智负担
    test2: {
      call() {
        document.title =  this.state.x.y.z;
      },
      deps: ['x.y.z'],
      immediate: false,
    },

    // 方案三:类似二,但是deps不再是字符串,能稍微减轻一点负担。
    test3: {
      call() {
        document.title =  this.state.x.y.z;
      },
      deps() {
        return [this.state.x.y.z];
      },
      immediate: false,
    },

  }
});

不完美的方案,用起来不爽,所以还得再发酵一段时间。

@geekact geekact pinned this issue May 6, 2022
@geekact geekact added the help wanted Extra attention is needed label May 6, 2022
@geekact
Copy link
Member Author

geekact commented May 7, 2022

如果包含异步,收集将受阻。但是vue3的watchEffect做到了?

@geekact geekact unpinned this issue Dec 22, 2022
@fantasticsoul
Copy link

方式1,透传一个isFirstCall 即可

watch((params)=>{
  const { c } = state.a.b; // 收集到依赖
  if(params.isFirstCall) return; // 不执行具体逻辑
  document.title = c;
})

方式二,类vue,先指定依赖,再设定回调

watch(()=>[ state.a.b.c ], ()=>  document.title = state.a.b.c )

欢迎是用limu来做深依赖收集,它是当前最快的不可变数据js库了,一篇掘金介绍
剑指immer,更快更强的limu稳定版发布

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
help wanted Extra attention is needed
Projects
None yet
Development

No branches or pull requests

2 participants