vueuse 核心api
供自己学习使用。代码来源于elementplus。后续看情况是否增加说明
isClient |
|
|
useStorage |
const userPrefer = useStorage<boolean | string>(USER_PREFER_GITHUB_PAGE, null) |
存储 |
useToggle |
const [isSidebarOpen, toggleSidebar] = useToggle(false)
<VPOverlay class="overlay" :show="isSidebarOpen" @click="toggleSidebar(false)" />
|
开关 |
useClipboard |
const { copy, isSupported } = useClipboard({ source: decodeURIComponent(props.rawSource), read: false, })
const copyCode = async () => { const { $message } = vm.appContext.config.globalProperties if (!isSupported) { $message.error(locale.value['copy-error']) } try { await copy() $message.success(locale.value['copy-success']) } catch (e: any) { $message.error(e.message) } }
|
使用剪切板 |
useCssVar |
const primary = useCssVar('--el-color-primary')
<div class="bg-color-sub" :style="{ background: primary }"> <div v-for="level in colorLevel" :key="level" class="bg-blue-sub-item cursor-pointer hover:shadow" :style="{ width: `${100 / 6}%`, background: 'var(--el-color-primary-' + level + ')', }" @click="copyColor('primary-' + level)" /> </div> </div>
|
|
useEventListener |
useEventListener(window, 'scroll', handleScroll) |
事件操作的封装,可以自动卸载事件 |
useThrottleFn |
const handleScroll = useThrottleFn(() => { const ele = jumbotronRef.value if (ele) { const rect = ele.getBoundingClientRect() const eleHeight = ele.clientHeight let calHeight = (180 - rect.top) * 2 if (calHeight < 0) calHeight = 0 if (calHeight > eleHeight) calHeight = eleHeight jumbotronRedOffset.value = calHeight } }, 10) |
节流 |
useElementBounding |
<template> <div ref="root"> </div> </template>
const target = shallowRef<HTMLElement>()
const { height: rootHeight, width: rootWidth, top: rootTop, bottom: rootBottom, update: updateRoot, } = useElementBounding(root) const targetRect = useElementBounding(target) |
|
useWindowSize |
const { height: windowHeight } = useWindowSize() |
|
onClickOutside |
<div ref="listboxRef" :class="[ns.b(), $attrs.class]" :style="styles" role="combobox" aria-haspopup="listbox" :aria-expanded="suggestionVisible" :aria-owns="listboxId" >
</div>
const listboxRef = ref<HTMLElement>()
onClickOutside(listboxRef, () => { suggestionVisible.value && close() }) |
|
useResizeObserver |
const resizeObserver = shallowRef<ReturnType<typeof useResizeObserver>>()
function resetItemPosition(oldIndex?: number) { items.value.forEach((item, index) => { item.translateItem(index, activeIndex.value, oldIndex) }) }
// lifecycle onMounted(async () => { await nextTick() resizeObserver.value = useResizeObserver(root.value, () => { resetItemPosition() }) }) onBeforeUnmount(() => { if (root.value && resizeObserver.value) resizeObserver.value.stop() })
|
|
refDebounced |
const validateState = ref<FormItemValidateState>('') const validateStateDebounced = refDebounced(validateState, 100)
const shouldShowError = computed( () => validateStateDebounced.value === 'error' && props.showMessage && (formContext?.showMessage ?? true) )
|
|
useTimeoutFn |
timeout?.() ;({ stop: timeout } = useTimeoutFn(() => { rootMenu.openMenu(props.index, indexPath.value) }, showTimeout)) |
|
unrefElement |
virtualEl : MaybeRef<Measurable | undefined | ComponentPublicInstance>
triggerRef.value = unrefElement(virtualEl as HTMLElement) |
|
useDocumentVisibility |
const visibility = useDocumentVisibility()
const focusable = ref(true)
watch(visibility, (visibility) => { if (visibility === 'hidden') { focusable.value = false } else if (visibility === 'visible') { setTimeout(() => (focusable.value = true), 50) } })
|
|
useWindowFocus |
return ( <div ref={`tab-${tabName}`} class={[ ns.e('item'), ns.is(rootTabs.props.tabPosition), ns.is('active', pane.active), ns.is('disabled', disabled), ns.is('closable', closable), ns.is('focus', isFocus.value), ]} id={`tab-${tabName}`} key={`tab-${tabName}`} aria-controls={`pane-${tabName}`} role="tab" aria-selected={pane.active} tabindex={tabindex} onFocus={() => setFocus()} onBlur={() => removeFocus()} onClick={(ev: MouseEvent) => { removeFocus() props.onTabClick(pane, tabName, ev) }} onKeydown={(ev: KeyboardEvent) => { if ( closable && (ev.code === EVENT_CODE.delete || ev.code === EVENT_CODE.backspace) ) { props.onTabRemove(pane, ev) } }} > {...[tabLabelContent, btnClose]} </div> ) })
const isFocus = ref(false)
const focused = useWindowFocus()
watch(focused, (focused) => { if (focused) { setTimeout(() => (focusable.value = true), 50) } else { focusable.value = false } })
const setFocus = () => { if (focusable.value) isFocus.value = true }
|
|
eagerComputed |
const active = eagerComputed( () => tabsRoot.currentName.value === (props.name ?? index.value) ) |
堕性计算 |
useVModel |
const uploadFiles = useVModel( props as Omit<UploadProps, 'fileList'> & { fileList: UploadFiles }, 'fileList', undefined, { passive: true } ) |
|
tryOnScopeDispose |
const cancelTimeout = () => window.clearTimeout(timeoutHandle)
tryOnScopeDispose(() => cancelTimeout()) |
用于把stop()方法注册到当前活跃的effect作用域上,这个活跃的effect作用域结束之后会将stop当作回调函数调用。
在当前作用域结束后执行某个清理副作用的功能 |