Subscribe on changes!

[lifecycle]: return cancel function to remove listener of lifecycle hook

avatar
Aug 9th 2021

What problem does this feature solve?

There is a scene, I want to cancel the unfinished request when the component is unMounted.

import { getCurrentInstance, onUnmounted } from "vue";
import { useApi } from '@/api';

const http = useApi(getCurrentInstance(), onUnmounted)

// send http request
// the request will be abort when component is Unmounted
http.get("/v1/foo/bar")

But, It will registry the onUnmounted on every request, if there are many requests, so there will be a lot of listeners.

So if the life cycle can return a Cancel function, I can accurately control the registration and destruction of the life cycle.

What does the proposed API look like?

import { onUnmounted } from 'vue'

const cancelUnmountedHook = onUnmounted(() => {
  console.log('clear somthing')
})

cancelUnmountedHook() // cancel the hook
avatar
Aug 9th 2021

duplicate of #4277