Skip to content

Commit

Permalink
fix(usePageLeave): close vueuse#207
Browse files Browse the repository at this point in the history
  • Loading branch information
antfu committed Nov 14, 2020
1 parent 910448b commit 0f99800
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 8 deletions.
10 changes: 4 additions & 6 deletions packages/core/usePageLeave/index.stories.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,17 +12,15 @@ defineDemo(
defineComponent({
setup() {
return {
isLeft: usePageLeave(),
isLeft: usePageLeave({
window: window.parent,
}),
}
},

template: html`
<div>
<pre lang="json">{{
JSON.stringify({
isLeft,
}, null, 2)
}}</pre>
<pre lang="json">{{ { isLeft } }}</pre>
</div>
`,
}),
Expand Down
12 changes: 10 additions & 2 deletions packages/core/usePageLeave/index.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,25 @@
import { ref } from 'vue-demi'
import { useEventListener } from '../useEventListener'
import { ConfigurableWindow, defaultWindow } from '../_configurable'

export function usePageLeave() {
export function usePageLeave({ window = defaultWindow }: ConfigurableWindow = {}) {
const isLeft = ref(false)

const handler = (event: MouseEvent) => {
if (!window)
return

event = event || (window.event as any)
// @ts-ignore
const from = event.relatedTarget || event.toElement
isLeft.value = !from
}

useEventListener('mouseout', handler)
if (window) {
useEventListener('mouseout', handler, undefined, window)
useEventListener('mouseleave', handler, undefined, window.document)
useEventListener('mouseenter', handler, undefined, window.document)
}

return isLeft
}

0 comments on commit 0f99800

Please sign in to comment.