vue#onBeforeUnmount TypeScript Examples

The following examples show how to use vue#onBeforeUnmount. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: utils.ts    From hexon with GNU General Public License v3.0 7 votes vote down vote up
function useResize(elRef: Ref<HTMLElement | null>, rect: Ref<IRect>) {
  const removeEventListenerFnMap: Map<() => void, () => void> = new Map()
  const removeAllEventListener = () => {
    for (const [, fn] of removeEventListenerFnMap) {
      fn()
    }
    removeEventListenerFnMap.clear()
  }
  watch(
    () => unref(elRef.value),
    (el) => {
      removeAllEventListener()
      if (!el) return
      const resiableNodesSet: Set<Element | Document> = new Set()
      let cursor: Element | Document | null = el
      while (true) {
        cursor = getScrollParent(cursor)
        if (cursor === null) break
        resiableNodesSet.add(cursor)
      }
      for (const node of [...resiableNodesSet, window]) {
        const onResize = () => {
          if (!elRef.value) return
          rect.value = getRect(elRef.value)
        }
        node.addEventListener("resize", onResize)
        removeEventListenerFnMap.set(onResize, () => {
          node.removeEventListener("resize", onResize)
        })
      }
    },
    {
      immediate: true,
    }
  )
  onBeforeUnmount(() => {
    removeAllEventListener()
  })
}
Example #2
Source File: on-fonts-ready.ts    From vooks with MIT License 6 votes vote down vote up
/**
 * Call callback on fontsReady is resolved. If fontsReady is already resolved,
 * callback won't be called.
 */
export default function onFontsReady (cb: () => any): void {
  /* istanbul ignore next */
  if (isFontReady) return
  let deactivated = false
  onMounted(() => {
    /* istanbul ignore next */
    if (!isFontReady) {
      fontsReady?.then(() => {
        if (deactivated) return
        cb()
      })
    }
  })
  onBeforeUnmount(() => {
    deactivated = true
  })
}
Example #3
Source File: use-click-position.ts    From vooks with MIT License 6 votes vote down vote up
export default function useClickPosition (): Readonly<
Ref<MousePosition | null>
> {
  if (!isBrowser) return readonly(ref(null))
  if (usedCount === 0) on('click', document, clickHandler as any, true)
  const setup = (): void => {
    usedCount += 1
  }
  if (managable && (managable = hasInstance())) {
    onBeforeMount(setup)
    onBeforeUnmount(() => {
      usedCount -= 1
      if (usedCount === 0) off('click', document, clickHandler as any, true)
    })
  } else {
    setup()
  }
  return readonly(mousePositionRef)
}
Example #4
Source File: use-clicked.ts    From vooks with MIT License 6 votes vote down vote up
export default function useClicked (timeout: number): Readonly<Ref<boolean>> {
  if (!isBrowser) return readonly(ref(false))
  const clickedRef = ref(false)
  let timerId: number | null = null
  function clearTimer (): void {
    if (timerId !== null) window.clearTimeout(timerId)
  }
  function clickedHandler (): void {
    clearTimer()
    clickedRef.value = true
    timerId = window.setTimeout(() => {
      clickedRef.value = false
    }, timeout)
  }
  if (usedCount === 0) {
    on('click', window, handleClick, true)
  }
  const setup = (): void => {
    usedCount += 1
    on('click', window, clickedHandler, true)
  }
  if (managable && (managable = hasInstance())) {
    onBeforeMount(setup)
    onBeforeUnmount(() => {
      usedCount -= 1
      if (usedCount === 0) {
        off('click', window, handleClick, true)
      }
      off('click', window, clickedHandler, true)
      clearTimer()
    })
  } else {
    setup()
  }
  return readonly(clickedRef)
}
Example #5
Source File: use-now.ts    From vooks with MIT License 6 votes vote down vote up
function useNow (
  interval: boolean | number,
  { type = 'number' }: UseNowOptions
): Ref<number | Date> {
  const isNumber = type === 'number'
  const nowRef = ref(isNumber ? Date.now() : new Date())
  if (interval === false) {
    let id: number
    onBeforeMount(() => {
      id = setInterval(() => {
        nowRef.value = isNumber ? Date.now() : new Date()
      }) as unknown as number
    })
    onBeforeUnmount(() => {
      clearInterval(id)
    })
  }
  return nowRef
}
Example #6
Source File: use-os-theme.ts    From vooks with MIT License 6 votes vote down vote up
export default function useOsTheme (): Readonly<Ref<Theme | null>> {
  /* istanbul ignore next */
  if (process.env.NODE_ENV !== 'test' && !supportMatchMedia) {
    return readonly(osTheme)
  }
  if (process.env.NODE_ENV === 'test' && window.matchMedia === undefined) {
    return readonly(osTheme)
  }
  if (usedCount === 0) init()
  if (managable && (managable = hasInstance())) {
    onBeforeMount(() => {
      usedCount += 1
    })
    onBeforeUnmount(() => {
      usedCount -= 1
      if (usedCount === 0) clean()
    })
  }
  return readonly(osTheme)
}
Example #7
Source File: useEventListener.ts    From elenext with MIT License 6 votes vote down vote up
function useEventListener(
  target: Ref<HTMLElement | Window | null>,
  type: string,
  listener: EventListenerOrEventListenerObject,
  options?: boolean | AddEventListenerOptions
): () => void {
  let prevEle: HTMLElement | Window | null = null
  const destroyWatcher = watchEffect(
    () => {
      target.value?.addEventListener(type, listener, options)
      if (prevEle) {
        prevEle.removeEventListener(type, listener)
      }
      prevEle = target?.value
    },
    { flush: 'post' }
  )
  const removeListener = (isDestroyWatcher = true) => {
    target.value?.removeEventListener(type, listener)
    if (isDestroyWatcher) {
      destroyWatcher()
    }
  }
  onBeforeUnmount(() => {
    removeListener(true)
  })
  return removeListener
}
Example #8
Source File: use-mount.ts    From fect with MIT License 6 votes vote down vote up
useMounted = (fns: MountedFn[]) => {
  if (!isArray(fns)) {
    console.log('[Fect] useMounted must entry array')
    return
  }

  const filterFunc = (fns: MountedFn[]) => {
    const single = len(fns) === 1
    if (single)
      return {
        start: fns[0],
        end: fns[0]
      }
    const [start, ...ends] = fns
    return {
      start,
      end: ends
    }
  }

  const { start, end } = filterFunc(fns)

  onMounted(start)

  onBeforeUnmount(() => {
    if (isArray(end)) {
      end.forEach((_) => _.apply(null))
      return
    }
    end()
    return
  })
}
Example #9
Source File: use-event-listener.ts    From fect with MIT License 6 votes vote down vote up
useEventListener = (
  event: EventTypes,
  listener: EventListenerOrEventListenerObject,
  options: Options = {}
) => {
  const { target = window, ...rest } = options

  const remove = (el: Options['target']) => {
    const _el = unref(el)
    _el && _el.removeEventListener(event, listener, rest)
  }

  const add = (el: Options['target']) => {
    const _el = unref(el)
    _el && _el.addEventListener(event, listener, rest)
  }

  watch(
    () => unref(target),
    (el, prevEl) => {
      remove(prevEl)
      add(el)
    }
  )

  onMounted(() => add(target))
  onDeactivated(() => remove(target))
  onBeforeUnmount(() => remove(target))
}
Example #10
Source File: use-title.ts    From fect with MIT License 6 votes vote down vote up
useTitle = (initialTitle = '') => {
  const [title, setTitle] = useState<string>(initialTitle)

  const titleChange = (title = '') => setTitle(title)

  const setDocumentTitle = () => (document.title = title.value)
  const resetDocumentTitle = () => (document.title = '')

  onMounted(setDocumentTitle)

  watch(title, setDocumentTitle)

  onBeforeUnmount(resetDocumentTitle)
  onDeactivated(resetDocumentTitle)

  return {
    titleChange,
    title
  }
}
Example #11
Source File: scroll.ts    From hexon with GNU General Public License v3.0 6 votes vote down vote up
export function useOnParentScroll(
  elRef: Ref<HTMLElement | null>,
  onScroll: () => void
) {
  const removeEventListenerFnMap: Map<() => void, () => void> = new Map()
  const removeAllEventListener = () => {
    for (const [, fn] of removeEventListenerFnMap) {
      fn()
    }
    removeEventListenerFnMap.clear()
  }
  watch(
    () => elRef.value,
    (el) => {
      removeAllEventListener()
      if (!el) return
      const scrollableNodesSet: Set<Element | Document> = new Set()
      let cursor: Element | Document | null = el
      while (true) {
        cursor = getScrollParent(cursor)
        if (cursor === null) break
        scrollableNodesSet.add(cursor)
      }
      for (const node of scrollableNodesSet) {
        node.addEventListener("scroll", onScroll)
        removeEventListenerFnMap.set(onScroll, () => {
          node.removeEventListener("scroll", onScroll)
        })
      }
    },
    {
      immediate: true,
    }
  )
  onBeforeUnmount(() => {
    removeAllEventListener()
  })
}
Example #12
Source File: use-breakpoints.ts    From vooks with MIT License 5 votes vote down vote up
function useBreakpoints<T extends BreakpointOptions> (
  screens: T = defaultBreakpointOptions as unknown as T
): ComputedRef<Array<ExtractBreakpoint<T>>> {
  if (!isBrowser) return computed(() => [])
  // eslint-disable-next-line @typescript-eslint/strict-boolean-expressions
  if (typeof window.matchMedia !== 'function') return computed(() => [])

  type BreakpointStatus = ExtractBreakpointStatus<T>

  const breakpointStatusRef = ref<BreakpointStatus>({} as BreakpointStatus)
  const breakpoints = Object.keys(screens)

  const updateBreakpoints: OnMqlChange = (e, breakpointName) => {
    if (e.matches) breakpointStatusRef.value[breakpointName] = true
    else breakpointStatusRef.value[breakpointName] = false
  }

  breakpoints.forEach((key) => {
    const breakpointValue = screens[key]
    let mql: MediaQueryList
    let cbs: Set<OnMqlChange>
    if (mqlMap[breakpointValue] === undefined) {
      mql = window.matchMedia(createMediaQuery(breakpointValue))
      // eslint-disable-next-line @typescript-eslint/strict-boolean-expressions
      if (mql.addEventListener) {
        mql.addEventListener('change', (e: MediaQueryListEvent) => {
          cbs.forEach((cb) => {
            cb(e, key)
          })
        })
        // eslint-disable-next-line @typescript-eslint/strict-boolean-expressions
      } else if (mql.addListener) {
        mql.addListener((e: MediaQueryListEvent) => {
          cbs.forEach((cb) => {
            cb(e, key)
          })
        })
      }

      cbs = new Set()
      mqlMap[breakpointValue] = {
        mql,
        cbs
      }
    } else {
      mql = mqlMap[breakpointValue].mql
      cbs = mqlMap[breakpointValue].cbs
    }
    cbs.add(updateBreakpoints)
    if (mql.matches) {
      cbs.forEach((cb) => {
        cb(mql, key)
      })
    }
  })

  onBeforeUnmount(() => {
    breakpoints.forEach((breakpoint) => {
      const { cbs } = mqlMap[screens[breakpoint]]
      if (cbs.has(updateBreakpoints)) {
        cbs.delete(updateBreakpoints)
      }
    })
  })

  return computed<Array<ExtractBreakpoint<T>>>(() => {
    const { value } = breakpointStatusRef
    return breakpoints.filter((key) => value[key]) as any
  })
}
Example #13
Source File: useSpreadSheet.ts    From S2 with MIT License 5 votes vote down vote up
export function useSpreadSheet(
  props: BaseSheetProps,
  emit: EmitFn<BaseSheetInitEmits>,
) {
  const {
    dataCfg,
    options,
    themeCfg,
    loading: loadingProps,
    sheetType,
    onSpreadsheet,
    onGetSpreadSheet,
  } = props;
  const wrapperRef = ref<HTMLDivElement>();
  const containerRef = ref<HTMLDivElement>();

  const s2Ref = shallowRef<SpreadSheet>();

  const { loading, setLoading } = useLoading(s2Ref, loadingProps);
  const pagination = usePagination(s2Ref, props);

  // TODO: 如果onSpreadsheet属性变更了怎么办???
  const renderSpreadSheet = (container: HTMLDivElement) => {
    const rawDataCfg = toRaw(dataCfg!);
    const rawOptions = toRaw(options);

    const s2Options = getSheetComponentOptions(rawOptions as S2Options);
    const s2Constructor: S2Constructor = [container, rawDataCfg, s2Options];
    if (onSpreadsheet) {
      return onSpreadsheet(...s2Constructor);
    }
    if (sheetType === 'table') {
      return new TableSheet(container, rawDataCfg, s2Options);
    }
    return new PivotSheet(container, rawDataCfg, s2Options);
  };

  const buildSpreadSheet = () => {
    setLoading(true);
    s2Ref.value = renderSpreadSheet(containerRef.value!);
    s2Ref.value.setThemeCfg(toRaw(themeCfg));
    s2Ref.value.render();
    setLoading(false);
    onGetSpreadSheet?.(s2Ref.value);
  };

  onMounted(buildSpreadSheet);
  useEvents(s2Ref, emit);
  useSheetUpdate(s2Ref, props);
  useResize(s2Ref, props, { wrapperRef, containerRef });

  onBeforeUnmount(() => {
    s2Ref.value?.destroy();
  });

  return {
    wrapperRef,
    containerRef,
    s2Ref,
    loading,
    setLoading,
    pagination,
  };
}
Example #14
Source File: use-keyboard.ts    From vooks with MIT License 4 votes vote down vote up
export default function useKeyboard (
  options: useKeyboardOptions = {},
  enabledRef?: Ref<boolean>
): Readonly<UseKeyboardState> {
  const state = reactive<UseKeyboardState>({
    ctrl: false,
    command: false,
    win: false,
    shift: false,
    tab: false
  })
  const {
    keydown,
    keyup
  } = options
  const keydownHandler = (e: KeyboardEvent): void => {
    switch (e.key) {
      case 'Control':
        state.ctrl = true
        break
      case 'Meta':
        state.command = true
        state.win = true
        break
      case 'Shift':
        state.shift = true
        break
      case 'Tab':
        state.tab = true
        break
    }
    if (keydown !== undefined) {
      Object.keys(keydown).forEach(key => {
        if (key !== e.key) return
        const handler = keydown[key]
        if (typeof handler === 'function') {
          handler(e)
        } else {
          const { stop = false, prevent = false } = handler
          if (stop) e.stopPropagation()
          if (prevent) e.preventDefault()
          handler.handler(e)
        }
      })
    }
  }
  const keyupHandler = (e: KeyboardEvent): void => {
    switch (e.key) {
      case 'Control':
        state.ctrl = false
        break
      case 'Meta':
        state.command = false
        state.win = false
        break
      case 'Shift':
        state.shift = false
        break
      case 'Tab':
        state.tab = false
        break
    }
    if (keyup !== undefined) {
      Object.keys(keyup).forEach(key => {
        if (key !== e.key) return
        const handler = keyup[key]
        if (typeof handler === 'function') {
          handler(e)
        } else {
          const { stop = false, prevent = false } = handler
          if (stop) e.stopPropagation()
          if (prevent) e.preventDefault()
          handler.handler(e)
        }
      })
    }
  }
  const setup = (): void => {
    if (enabledRef === undefined || enabledRef.value) {
      on('keydown', document, keydownHandler)
      on('keyup', document, keyupHandler)
    }
    if (enabledRef !== undefined) {
      watch(enabledRef, value => {
        if (value) {
          on('keydown', document, keydownHandler)
          on('keyup', document, keyupHandler)
        } else {
          off('keydown', document, keydownHandler)
          off('keyup', document, keyupHandler)
        }
      })
    }
  }
  if (hasInstance()) {
    onBeforeMount(setup)
    onBeforeUnmount(() => {
      if (enabledRef === undefined || enabledRef.value) {
        off('keydown', document, keydownHandler)
        off('keyup', document, keyupHandler)
      }
    })
  } else {
    setup()
  }
  return readonly(state)
}