-
-
Notifications
You must be signed in to change notification settings - Fork 8.3k
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
feat(watch): accept watch callback return cleanup function #11664
base: main
Are you sure you want to change the base?
Conversation
Size ReportBundles
Usages
|
@vue/compiler-dom
@vue/compiler-core
@vue/compiler-ssr
@vue/compiler-sfc
@vue/reactivity
@vue/runtime-dom
@vue/runtime-core
@vue/server-renderer
@vue/shared
vue
@vue/compat
commit: |
The problem with this is the behavior is inconsistent between async and non-async functions (This can be enforced via types, i.e. there should be a type error if the callback is an async function and returns a function). We also need to think about the consistency between effect ( |
To ensure the return value behaves consistently with The implementation might look like this: const cleanup = call
? call(cb!, WatchErrorCodes.WATCH_CALLBACK, args)
: // @ts-expect-error
cb!(...args)
if (isFunction(cleanup)) {
boundCleanup(cleanup)
} else if (isPromise(cleanup)) {
cleanup.then(result => {
if (isFunction(result)) boundCleanup(result)
})
} This approach would make its effect consistent with |
# Conflicts: # packages/reactivity/__tests__/watch.spec.ts
In the current version, we can clear the callback side effects using
watch
as follows:After version 3.5.0-beta.3, we can use
onWatcherCleanup
to clear side effects:This pull request proposes discussing the possibility of introducing a method to support returning a function as one way of cleanup.
The inspiration for this approach comes from React’s
useEffect
:I believe this could be particularly friendly for developers transitioning from React to Vue, hence my initiative to introduce it here.
However, this might introduce some migration costs, such as when using arrow functions:
Here, the callback returns a number, which clearly isn't a cleanup function. Therefore, in implementation, it would only collect as a cleanup function if the return is a function. From my personal experience, it is uncommon to return a function in this context, so the impact should be minimal.
I would be most grateful for any feedback on this approach. If there are any concerns or alternative suggestions, please do not hesitate to share them. I am eager to make any necessary adjustments to accommodate community insights.