feat(watch): accept watch callback return cleanup function #11664
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
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.