vue#Ref TypeScript Examples
The following examples show how to use
vue#Ref.
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 | 8 votes |
export function useAsyncComponentWithLoading(
loader: Parameters<typeof defineAsyncComponent>[0]
): [ReturnType<typeof defineAsyncComponent>, ComputedRef<boolean>] {
const loading = ref(true)
const _loader = "loader" in loader ? loader.loader : loader
return [
defineAsyncComponent(() =>
_loader().then((res) => {
loading.value = false
return res
})
),
computed(() => loading.value),
]
}
Example #2
Source File: reactivity-utils.ts From quantum-sheet with GNU General Public License v3.0 | 7 votes |
export function untilDefined<T>(source: Ref<T>): Promise<T> {
return new Promise((resolve) => {
const stopHandle = watch(source, (value) => {
if (value !== undefined && value !== null) {
stopHandle()
resolve(value)
}
})
})
}
Example #3
Source File: utils.ts From vue-i18n-next with MIT License | 7 votes |
/* eslint-enable */
export function useDebouncedRef<T>(value: T, delay = 200): Ref<T> {
let timeout: ReturnType<typeof setTimeout>
return customRef<T>((track, trigger) => {
return {
get() {
track()
return value
},
set(newValue: T) {
clearTimeout(timeout)
timeout = setTimeout(() => {
value = newValue
trigger()
}, delay)
}
}
})
}
Example #4
Source File: utils.ts From hexon with GNU General Public License v3.0 | 7 votes |
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 #5
Source File: auth.ts From quasar-app-extension-http-authentication with MIT License | 6 votes |
usePasswordForgot = ({ router }: { router?: Router} = {}) => {
/**
* Replace with your own function
*/
const $q = useQuasar()
const lang = useLang()
const loading = ref(false)
const result = ref()
const fetch = (user: Ref<unknown>) => {
loading.value = true
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve('200')
}, 1000)
}).then((res: unknown) => {
result.value = res
checkEmailDialog($q, {
onOk: () => router?.push('/login')
}, lang)
return res
}).catch((res: unknown) => {
return unknownEmailDialog($q, {}, lang)
}).finally(() => {
loading.value = false
})
}
return { result, loading, fetch }
}
Example #6
Source File: usePlocState.ts From frontend-clean-architecture with MIT License | 6 votes |
export function usePlocState<S>(ploc: Ploc<S>): DeepReadonly<Ref<S>> {
const state = ref(ploc.state) as Ref<S>;
const stateSubscription = (newState: S) => {
state.value = newState;
};
onMounted(() => {
ploc.subscribe(stateSubscription);
});
onUnmounted(() => {
ploc.unsubscribe(stateSubscription);
});
return readonly(state);
}
Example #7
Source File: helpers.ts From quasar-app-extension-http-authentication with MIT License | 6 votes |
logoutDialog = ($q: QVueGlobals, callbacks: { onOk?: Function, onCancel?: Function }, lang: Ref<Language>) => {
createDialog({
$q,
title: lang.value.auth.logout.confirm,
message: lang.value.auth.logout.confirmation,
ok: lang.value.auth.logout.logout,
cancel: lang.value.auth.logout.cancel
})(callbacks)
}
Example #8
Source File: utils.ts From vue3-datagrid with MIT License | 6 votes |
getElementClasses = (ref: Ref<HTMLElement | undefined>, componentClasses: Set<string>, defaultClasses: string[] = []) => {
return [ ...Array.from(ref.value?.classList || []), ...defaultClasses ]
.filter((c: string, i, self) => !componentClasses.has(c) && self.indexOf(c) === i);
}
Example #9
Source File: useRight.ts From am-editor with MIT License | 6 votes |
useRight = (button: Ref<HTMLElement | null>) => {
const isRight = ref(false);
onMounted(() => {
if (button.value && isMobile) {
const rect = button.value.getBoundingClientRect();
isRight.value = rect.left > window.visualViewport.width / 2;
}
});
return isRight;
}
Example #10
Source File: vue.ts From keen-slider with MIT License | 6 votes |
export function useKeenSlider<
T extends HTMLElement,
O = {},
P = {},
H extends string = KeenSliderHooks
>(
options: Ref<KeenSliderOptions<O, P, H>> | KeenSliderOptions<O, P, H>,
plugins?: KeenSliderPlugin<O, P, H>[]
): [Ref<T | undefined>, Ref<KeenSliderInstance<O, P, H> | undefined>] {
const container = ref<T>()
const slider = ref<KeenSliderInstance<O, P, H>>()
if (isRef(options)) {
watch(options, (newOptions, _) => {
if (slider.value) slider.value.update(newOptions)
})
}
onMounted(() => {
if (container.value)
slider.value = new KeenSlider<O, P, H>(
container.value,
isRef(options) ? options.value : options,
plugins
)
})
onUnmounted(() => {
if (slider.value) slider.value.destroy()
})
return [container, slider]
}
Example #11
Source File: useStorage.test.ts From vhook with MIT License | 6 votes |
function testStorageWithObject (storage: Storage) {
describe('test useStorage when storage is storage and val is an Object', () => {
let state: Ref<{ a: number} | null>
let setState: (val?: { a: number }) => void
beforeEach(() => {
[state, setState] = useStorage('test', { a: 1 }, storage)
})
test('initial value of key test in storage is 1', () => {
expect(storage.getItem('test')).toBe(JSON.stringify({ a: 1 }))
expect(state.value).toEqual({ a: 1 })
})
test('value of key test in storage should change when invoking setState with new value', () => {
setState({ a: 2 })
expect(storage.getItem('test')).toBe(JSON.stringify({ a: 2 }))
expect(state.value).toEqual({ a: 2 })
})
test('key test in storage should be removed when invoking setState with no parameter or undefined', () => {
setState()
expect(storage.getItem('test')).toBeNull()
expect(state.value).toBeNull()
setState({ a: 1 })
expect(storage.getItem('test')).toBe(JSON.stringify({ a: 1 }))
expect(state.value).toEqual({ a: 1 })
setState(undefined)
expect(storage.getItem('test')).toBeNull()
expect(state.value).toBeNull()
})
})
}
Example #12
Source File: index.ts From jz-gantt with MIT License | 6 votes |
useStore = () => {
return {
GtData: inject(Variables.provider.gtData) as GanttData,
GtParam: inject(Variables.provider.gtParam) as ParamData,
rootEmit: inject(Variables.provider.gtRootEmit) as Ref<any>,
rootRef: inject(Variables.provider.gtRootRef) as Ref<HTMLDivElement>,
ganttRef: inject(Variables.provider.gtGanttRef) as Ref<HTMLDivElement>,
tableRef: inject(Variables.provider.gtTableRef) as Ref<HTMLDivElement>,
isShowMask: inject(Variables.provider.gtIsShowMask) as Ref<boolean>,
showDateList: inject(Variables.provider.gtShowDateList) as Date[],
successBarList: inject(Variables.provider.gtSuccessBarList) as Row[],
initGanttWidth: inject(Variables.provider.gtInitGanttWidth) as Ref<number>,
columnSliderLineVisible: inject(
Variables.provider.gtColumnSliderLineVisible
) as Ref<boolean>,
columnSliderLineLeft: inject(
Variables.provider.gtColumnSliderLineLeft
) as Ref<number>,
columnDefaultLeft: inject(
Variables.provider.gtColumnDefaultLeft
) as Ref<number>,
successBarTimeout: inject(Variables.provider.gtSuccessBarTimeout) as number,
isShowToast: inject(Variables.provider.gtIsShowToast) as Ref<boolean>,
toastMessage: inject(Variables.provider.gtToastMessage) as Ref<string>,
toastQueue: inject(Variables.provider.gtToastQueue) as any[],
scrollTop: inject(Variables.provider.gtScrollTop) as Ref<number>,
rootHeight: inject(Variables.provider.gtRootHeight) as Ref<number>,
scrollBarHeight: inject(
Variables.provider.gtScrollBarHeight
) as Ref<number>,
stopClickEvent: inject(Variables.provider.gtStopClickEvent) as Ref<boolean>
};
}
Example #13
Source File: Translation.test.ts From vue-i18n-next with MIT License | 6 votes |
test('v-if / v-else', async () => {
const i18n = createI18n({
legacy: false,
locale: 'en',
messages
})
let toggle: Ref<boolean>
const App = defineComponent({
setup() {
useI18n()
toggle = ref(true)
return { toggle }
},
template: `
<i18n-t tag="p" class="name" keypath="message.named">
<template #name>
<span v-if="toggle">kazupon</span>
<span v-else="toggle">kazu_pon</span>
</template>
</i18n-t>
`
})
const wrapper = await mount(App, i18n)
expect(wrapper.html()).toEqual(
`<p class="name">hello, <span>kazupon</span>!</p>`
)
toggle!.value = false
await nextTick()
expect(wrapper.html()).toEqual(
`<p class="name">hello, <span>kazu_pon</span>!</p>`
)
})
Example #14
Source File: utils.ts From elements with MIT License | 6 votes |
getElementClasses = (ref: Ref<HTMLElement | undefined>, componentClasses: Set<string>, defaultClasses: string[] = []) => {
return [ ...Array.from(ref.value?.classList || []), ...defaultClasses ]
.filter((c: string, i, self) => !componentClasses.has(c) && self.indexOf(c) === i);
}
Example #15
Source File: scroll.ts From hexon with GNU General Public License v3.0 | 6 votes |
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 #16
Source File: watchVerbose.ts From formkit with MIT License | 6 votes |
/**
* "Touches" a given property for reactivity tracking purposes, if the value at
* the given path is an object, we flatten it to just its keys since we will
* already be tracking sub properties independently.
* @param obj - A ref to traverse for a given path
* @param path - An array of strings representing the path to locate
* @returns
*/
function touch(obj: Ref<any> | Record<string, any>, path: ObjectPath) {
const value = get(obj, path)
return value && typeof value === 'object' ? Object.keys(value) : value
}
Example #17
Source File: use-click-away.ts From fect with MIT License | 6 votes |
useClickAway = (
listener: EventListener,
target: Element | Ref<Element | undefined>,
options = defaultOptions
) => {
if (!isBrowser()) return
const onClick = (evt: Event) => {
const element = unref(target)
if (element && !element.contains(evt.target as Node)) {
listener(evt)
}
}
useEventListener(options.event!, onClick, { target: document })
}
Example #18
Source File: utils.ts From vue-hooks-form with MIT License | 6 votes |
isAllUnmounted = (fieldRefs?: Set<Ref>) => {
if (fieldRefs === undefined) {
return true
}
return [...fieldRefs].every(isUnmounted)
}
Example #19
Source File: productsApi.ts From master-frontend-lemoncode with MIT License | 6 votes |
useProductsApi = async (): Promise<{
list: Ref<Product[]>
totalProducts: ComputedRef<number>
}> => {
const list: Ref<Product[]> = ref([])
list.value = await productService.get()
const totalProducts = computed(() => {
return list.value.length
})
return { list, totalProducts }
}
Example #20
Source File: useSize.ts From elenext with MIT License | 6 votes |
useSize = (target: Ref<HTMLElement | Window | null>): Size => {
const width = ref(0)
const height = ref(0)
useEventListener(
target,
'resize',
() => {
width.value = window.innerWidth
height.value = window.innerHeight
},
{ passive: true }
)
return { width, height }
}
Example #21
Source File: use-os-theme.ts From vooks with MIT License | 6 votes |
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 #22
Source File: usePlocState.ts From frontend-clean-architecture with MIT License | 6 votes |
export function usePlocState<S>(ploc: Ploc<S>): DeepReadonly<Ref<S>> {
const state = ref(ploc.state) as Ref<S>;
const stateSubscription = (newState: S) => {
state.value = newState;
};
onMounted(() => {
ploc.subscribe(stateSubscription);
});
onUnmounted(() => {
ploc.unsubscribe(stateSubscription);
});
return readonly(state);
}
Example #23
Source File: tools.ts From trois with MIT License | 6 votes |
export function bindProp(src: any, srcProp: string, dst: any, dstProp?: string): void {
const _dstProp = dstProp || srcProp
const ref = toRef(src, srcProp)
if (ref.value instanceof Object) {
setFromProp(dst[_dstProp], ref.value)
watch(ref, (value) => { setFromProp(dst[_dstProp], value) }, { deep: true })
} else {
if (ref.value !== undefined) dst[_dstProp] = src[srcProp]
watch(ref, (value) => { dst[_dstProp] = value })
}
}
Example #24
Source File: auth.ts From quasar-app-extension-http-authentication with MIT License | 6 votes |
useVerify = ({ router }: { router?: Router} = {}) => {
/**
* Replace with your own function
*/
const $q = useQuasar()
const lang = useLang()
const loading = ref(false)
const result = ref()
const fetch = (token: string) => {
loading.value = true
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve('200')
}, 1000)
}).then((res: unknown) => {
result.value = res
verificationSuccessDialog($q, {
onOk: () => router?.push('/login')
}, lang)
return res
}).catch((res: unknown) => {
return verificationFailedDialog($q, {}, lang)
}).finally(() => {
loading.value = false
})
}
return { result, loading, fetch }
}
Example #25
Source File: use-false-until-truthy.spec.ts From vooks with MIT License | 6 votes |
describe('# useFalseUntilTruthy', () => {
it('works with init value `false`', async () => {
const originalRef = ref<any>(false)
const testRef = useFalseUntilTruthy(originalRef)
expect(testRef.value).toEqual(false)
originalRef.value = null
await nextTick()
expect(testRef.value).toEqual(false)
originalRef.value = true
await nextTick()
expect(testRef.value).toEqual(true)
originalRef.value = false
await nextTick()
expect(testRef.value).toEqual(true)
})
it('works with init value `true`', async () => {
const originalRef = ref(true)
const testRef = useFalseUntilTruthy(originalRef)
expect(testRef.value).toEqual(true)
originalRef.value = false
await nextTick()
expect(testRef.value).toEqual(true)
})
})
Example #26
Source File: auth.ts From quasar-app-extension-http-authentication with MIT License | 6 votes |
useRegister = ({ router }: { router?: Router} = {}) => {
/**
* Replace with your own function
*/
const $q = useQuasar()
const lang = useLang()
const loading = ref(false)
const result = ref()
const fetch = (user: Ref<unknown>) => {
loading.value = true
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve('200')
}, 1000)
}).then((res: unknown) => {
result.value = res
return res
}).catch((res: unknown) => {
if (res === '403') return invalidDataDialog($q, {}, lang)
if (res === '409') return alreadyRegisteredDialog($q, {}, lang)
return registrationErrorDialog($q, {}, lang)
}).finally(() => {
loading.value = false
})
}
return { result, loading, fetch }
}
Example #27
Source File: utils.ts From vue3-datagrid with MIT License | 6 votes |
getElementClasses = (ref: Ref<HTMLElement | undefined>, componentClasses: Set<string>, defaultClasses: string[] = []) => {
return [ ...Array.from(ref.value?.classList || []), ...defaultClasses ]
.filter((c: string, i, self) => !componentClasses.has(c) && self.indexOf(c) === i);
}
Example #28
Source File: useRight.ts From am-editor with MIT License | 6 votes |
useRight = (button: Ref<HTMLElement | null>) => {
const isRight = ref(false);
onMounted(() => {
if (button.value && isMobile) {
const rect = button.value.getBoundingClientRect();
isRight.value = rect.left > window.visualViewport.width / 2;
}
});
return isRight;
}
Example #29
Source File: vue.ts From keen-slider with MIT License | 6 votes |
export function useKeenSlider<
T extends HTMLElement,
O = {},
P = {},
H extends string = KeenSliderHooks
>(
options: Ref<KeenSliderOptions<O, P, H>> | KeenSliderOptions<O, P, H>,
plugins?: KeenSliderPlugin<O, P, H>[]
): [Ref<T | undefined>, Ref<KeenSliderInstance<O, P, H> | undefined>] {
const container = ref<T>()
const slider = ref<KeenSliderInstance<O, P, H>>()
if (isRef(options)) {
watch(options, (newOptions, _) => {
if (slider.value) slider.value.update(newOptions)
})
}
onMounted(() => {
if (container.value)
slider.value = new KeenSlider<O, P, H>(
container.value,
isRef(options) ? options.value : options,
plugins
)
})
onUnmounted(() => {
if (slider.value) slider.value.destroy()
})
return [container, slider]
}