Composition-api: WatchEffect's onCleanup is not firing when component is unmounted

Created on 25 Mar 2020  路  4Comments  路  Source: vuejs/composition-api

Greetings,

I am using watchEffect in a component that is loaded by router-view.
After the route is changed, this component is unmounted.
I was expecting onCleanup to fire at this time.
Is this a correct expectation?

To my humble information, vue-router does not cache routing components, so I am assuming they are being destroyed. If that is not the case, then how can I ensure proper cleanup while leveraging the router's cache?

Btw., the Vue Composition API official documentation is calling onCleanup as onInvalidate which was a bit confusing to me. May be I was on the wrong docs version.

Thank you.

bug has PR

Most helpful comment

Thanks. Confirmed and found the cause. Will submit a fix later this evening.

All 4 comments

Yes it should be called, provided that the watchEffect was created inside of setup(). Can you provide a reproduction?

My code also doesn't work ...


import { watchEffect, defineComponent } from '@vue/composition-api'

const listenOutsideRef = (handler, event, ref) => {
  if (!ref || ref.contains(event.target)) {
    console.log('no ref')
    return
  }
  handler(event)
}

const onClickOutside = (
  refs,
  refName,
  handler,
) => {
  watchEffect(onCleanup => {
    if (refs && refs[refName]) {
      const func = event => listenOutsideRef(handler, event, refs[refName])
      document.addEventListener('click', func)

     // not work 馃槩
      onCleanup(() => {
        console.log('destroy')
        document.removeEventListener('click', func)
      })
    }
  })
}

export default defineComponent({
  setup(_props, ctx) {
    onClickOutside(ctx.refs, 'myRef', () => {
      console.log('on click outside')
    })
  },
})

<template>
  <div ref="myRef" />
</template>

Thanks. Confirmed and found the cause. Will submit a fix later this evening.

PR done.

Note: I think the normal watch had the same bug, as the modified test failed just the same. Need someone else to have a second look though.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

rchaser53 picture rchaser53  路  4Comments

ycmjason picture ycmjason  路  5Comments

mbbbc picture mbbbc  路  6Comments

kwanjas3 picture kwanjas3  路  4Comments

gokhantaskan picture gokhantaskan  路  6Comments