vue#onBeforeMount TypeScript Examples
The following examples show how to use
vue#onBeforeMount.
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: use-click-position.ts From vooks with MIT License | 6 votes |
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 #2
Source File: use-clicked.ts From vooks with MIT License | 6 votes |
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 #3
Source File: use-now.ts From vooks with MIT License | 6 votes |
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 #4
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 #5
Source File: useBreakpoint.ts From elenext with MIT License | 6 votes |
function useBreakpoint() {
onBeforeMount(() => {
if (Object.keys(screens).length < RESPONSIVE_ARRAY.length) {
const keys = Object.keys(RESPONSIVE_MAP) as Breakpoint[]
keys.forEach(screen => {
const matchMediaQuery = RESPONSIVE_MAP[screen]!
const mql = window.matchMedia(matchMediaQuery)
const listener = (event: { matches: boolean }) => {
const { matches } = event
// console.log(event)
screens[screen] = matches
}
mql.addEventListener('change', listener)
// headlers[matchMediaQuery] = { mql, listener }
listener(mql)
})
}
})
return screens
}
Example #6
Source File: useResize.ts From jz-gantt with MIT License | 6 votes |
/**
* 监听甘特横向大小变化
*/
export function useResizeGanttObserver() {
const { initGanttWidth, setHeaders } = useSetGanttHeader();
const { ganttRef } = useGanttRef();
const ganttResizeObserver = ref<ResizeObserver>();
onBeforeMount(() => {
ganttResizeObserver.value = new ResizeObserver(entries => {
// eslint-disable-next-line no-restricted-syntax
for (const entry of entries) {
initGanttWidth.value = entry.contentRect.width;
setHeaders();
}
});
});
onMounted(() => {
// eslint-disable-next-line @typescript-eslint/no-unused-expressions
ganttRef?.value && ganttResizeObserver.value?.observe(ganttRef.value);
});
onUnmounted(() => {
ganttResizeObserver.value = undefined;
});
return {};
}
Example #7
Source File: use-keyboard.ts From vooks with MIT License | 4 votes |
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)
}
Example #8
Source File: i18n.ts From vue-i18n-next with MIT License | 4 votes |
function setupLifeCycle(
i18n: I18nInternal,
target: ComponentInternalInstance,
composer: Composer
): void {
let emitter: VueDevToolsEmitter | null = null
if (__BRIDGE__) {
// assign legacy VueI18n instance to Vue2 instance
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const vm = target.proxy as any
if (vm == null) {
throw createI18nError(I18nErrorCodes.UNEXPECTED_ERROR)
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const _i18n = (composer as any)[LegacyInstanceSymbol]
if (_i18n === i18n) {
throw createI18nError(I18nErrorCodes.UNEXPECTED_ERROR)
}
vm._i18n = _i18n
vm._i18n_bridge = true
// browser only
if (inBrowser) {
vm._i18nWatcher = vm._i18n.watchI18nData()
if (vm._i18n._sync) {
vm._localeWatcher = vm._i18n.watchLocale()
}
}
let subscribing = false
onBeforeMount(() => {
vm._i18n.subscribeDataChanging(vm)
subscribing = true
}, target)
onUnmounted(() => {
if (subscribing) {
vm._i18n.unsubscribeDataChanging(vm)
subscribing = false
}
if (vm._i18nWatcher) {
vm._i18nWatcher()
vm._i18n.destroyVM()
delete vm._i18nWatcher
}
if (vm._localeWatcher) {
vm._localeWatcher()
delete vm._localeWatcher
}
delete vm._i18n_bridge
delete vm._i18n
}, target)
} else {
onMounted(() => {
// inject composer instance to DOM for intlify-devtools
if (
(__DEV__ || __FEATURE_PROD_VUE_DEVTOOLS__) &&
!__NODE_JS__ &&
target.vnode.el
) {
target.vnode.el.__VUE_I18N__ = composer
emitter = createEmitter<VueDevToolsEmitterEvents>()
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const _composer = composer as any
_composer[EnableEmitter] && _composer[EnableEmitter](emitter)
emitter.on('*', addTimelineEvent)
}
}, target)
onUnmounted(() => {
// remove composer instance from DOM for intlify-devtools
if (
(__DEV__ || __FEATURE_PROD_VUE_DEVTOOLS__) &&
!__NODE_JS__ &&
target.vnode.el &&
target.vnode.el.__VUE_I18N__
) {
emitter && emitter.off('*', addTimelineEvent)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const _composer = composer as any
_composer[DisableEmitter] && _composer[DisableEmitter]()
delete target.vnode.el.__VUE_I18N__
}
i18n.__deleteInstance(target)
}, target)
}
}
Example #9
Source File: i18n.ts From vue-i18n-next with MIT License | 4 votes |
function useI18nForLegacy(
instance: ComponentInternalInstance,
scope: I18nScope,
root: Composer,
options: any = {} // eslint-disable-line @typescript-eslint/no-explicit-any
): Composer {
type Message = VueMessageType
const isLocale = scope === 'local'
const _composer = shallowRef<Composer | null>(null)
if (
isLocale &&
instance.proxy &&
!(instance.proxy.$options.i18n || instance.proxy.$options.__i18n)
) {
throw createI18nError(
I18nErrorCodes.MUST_DEFINE_I18N_OPTION_IN_ALLOW_COMPOSITION
)
}
const _inheritLocale = isBoolean(options.inheritLocale)
? options.inheritLocale
: true
const _locale = ref<Locale>(
// prettier-ignore
isLocale && _inheritLocale
? root.locale.value
: isString(options.locale)
? options.locale
: DEFAULT_LOCALE
)
const _fallbackLocale = ref<FallbackLocale>(
// prettier-ignore
isLocale && _inheritLocale
? root.fallbackLocale.value
: isString(options.fallbackLocale) ||
isArray(options.fallbackLocale) ||
isPlainObject(options.fallbackLocale) ||
options.fallbackLocale === false
? options.fallbackLocale
: _locale.value
)
const _messages = ref<LocaleMessages<LocaleMessage<Message>>>(
getLocaleMessages<LocaleMessages<LocaleMessage<Message>>>(
_locale.value as Locale,
options
)
)
// prettier-ignore
const _datetimeFormats = ref<DateTimeFormatsType>(
isPlainObject(options.datetimeFormats)
? options.datetimeFormats
: { [_locale.value]: {} }
)
// prettier-ignore
const _numberFormats = ref<NumberFormatsType>(
isPlainObject(options.numberFormats)
? options.numberFormats
: { [_locale.value]: {} }
)
// prettier-ignore
const _missingWarn = isLocale
? root.missingWarn
: isBoolean(options.missingWarn) || isRegExp(options.missingWarn)
? options.missingWarn
: true
// prettier-ignore
const _fallbackWarn = isLocale
? root.fallbackWarn
: isBoolean(options.fallbackWarn) || isRegExp(options.fallbackWarn)
? options.fallbackWarn
: true
// prettier-ignore
const _fallbackRoot = isLocale
? root.fallbackRoot
: isBoolean(options.fallbackRoot)
? options.fallbackRoot
: true
// configure fall back to root
const _fallbackFormat = !!options.fallbackFormat
// runtime missing
const _missing = isFunction(options.missing) ? options.missing : null
// postTranslation handler
const _postTranslation = isFunction(options.postTranslation)
? options.postTranslation
: null
// prettier-ignore
const _warnHtmlMessage = isLocale
? root.warnHtmlMessage
: isBoolean(options.warnHtmlMessage)
? options.warnHtmlMessage
: true
const _escapeParameter = !!options.escapeParameter
// prettier-ignore
const _modifiers = isLocale
? root.modifiers
: isPlainObject(options.modifiers)
? options.modifiers
: {}
// pluralRules
const _pluralRules = options.pluralRules || (isLocale && root.pluralRules)
// track reactivity
function trackReactivityValues() {
return [
_locale.value,
_fallbackLocale.value,
_messages.value,
_datetimeFormats.value,
_numberFormats.value
]
}
// locale
const locale = computed({
get: () => {
return _composer.value ? _composer.value.locale.value : _locale.value
},
set: val => {
if (_composer.value) {
_composer.value.locale.value = val
}
_locale.value = val
}
})
// fallbackLocale
const fallbackLocale = computed({
get: () => {
return _composer.value
? _composer.value.fallbackLocale.value
: _fallbackLocale.value
},
set: val => {
if (_composer.value) {
_composer.value.fallbackLocale.value = val
}
_fallbackLocale.value = val
}
})
// messages
const messages = computed<LocaleMessages<LocaleMessage<Message>, Message>>(
() => {
if (_composer.value) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
return _composer.value.messages.value as any
} else {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
return _messages.value as any
}
}
)
const datetimeFormats = computed<DateTimeFormatsType>(
() => _datetimeFormats.value
)
const numberFormats = computed<NumberFormatsType>(() => _numberFormats.value)
function getPostTranslationHandler(): PostTranslationHandler<Message> | null {
return _composer.value
? _composer.value.getPostTranslationHandler()
: _postTranslation
}
function setPostTranslationHandler(
handler: PostTranslationHandler<Message> | null
): void {
if (_composer.value) {
_composer.value.setPostTranslationHandler(handler)
}
}
function getMissingHandler(): MissingHandler | null {
return _composer.value ? _composer.value.getMissingHandler() : _missing
}
function setMissingHandler(handler: MissingHandler | null): void {
if (_composer.value) {
_composer.value.setMissingHandler(handler)
}
}
function warpWithDeps<R>(fn: () => unknown) {
trackReactivityValues()
return fn() as R
}
function t(...args: unknown[]): string {
return _composer.value
? warpWithDeps<string>(
() => Reflect.apply(_composer.value!.t, null, [...args]) as string
)
: warpWithDeps<string>(() => '')
}
function rt(...args: unknown[]): string {
return _composer.value
? Reflect.apply(_composer.value.rt, null, [...args])
: ''
}
function d(...args: unknown[]): string {
return _composer.value
? warpWithDeps<string>(
() => Reflect.apply(_composer.value!.d, null, [...args]) as string
)
: warpWithDeps<string>(() => '')
}
function n(...args: unknown[]): string {
return _composer.value
? warpWithDeps<string>(
() => Reflect.apply(_composer.value!.n, null, [...args]) as string
)
: warpWithDeps<string>(() => '')
}
function tm(key: Path): LocaleMessageValue<Message> | {} {
return _composer.value ? _composer.value.tm(key) : {}
}
function te(key: Path, locale?: Locale): boolean {
return _composer.value ? _composer.value.te(key, locale) : false
}
function getLocaleMessage(locale: Locale): LocaleMessage<Message> {
return _composer.value ? _composer.value.getLocaleMessage(locale) : {}
}
function setLocaleMessage(locale: Locale, message: LocaleMessage<Message>) {
if (_composer.value) {
_composer.value.setLocaleMessage(locale, message)
_messages.value[locale] = message
}
}
function mergeLocaleMessage(
locale: Locale,
message: LocaleMessageDictionary<Message>
): void {
if (_composer.value) {
_composer.value.mergeLocaleMessage(locale, message)
}
}
function getDateTimeFormat(locale: Locale): DateTimeFormat {
return _composer.value ? _composer.value.getDateTimeFormat(locale) : {}
}
function setDateTimeFormat(locale: Locale, format: DateTimeFormat): void {
if (_composer.value) {
_composer.value.setDateTimeFormat(locale, format)
_datetimeFormats.value[locale] = format
}
}
function mergeDateTimeFormat(locale: Locale, format: DateTimeFormat): void {
if (_composer.value) {
_composer.value.mergeDateTimeFormat(locale, format)
}
}
function getNumberFormat(locale: Locale): NumberFormat {
return _composer.value ? _composer.value.getNumberFormat(locale) : {}
}
function setNumberFormat(locale: Locale, format: NumberFormat): void {
if (_composer.value) {
_composer.value.setNumberFormat(locale, format)
_numberFormats.value[locale] = format
}
}
function mergeNumberFormat(locale: Locale, format: NumberFormat): void {
if (_composer.value) {
_composer.value.mergeNumberFormat(locale, format)
}
}
const wrapper = {
get id(): number {
return _composer.value ? _composer.value.id : -1
},
locale,
fallbackLocale,
messages,
datetimeFormats,
numberFormats,
get inheritLocale(): boolean {
return _composer.value ? _composer.value.inheritLocale : _inheritLocale
},
set inheritLocale(val: boolean) {
if (_composer.value) {
_composer.value.inheritLocale = val
}
},
get availableLocales(): Locale[] {
return _composer.value
? _composer.value.availableLocales
: Object.keys(_messages.value)
},
get modifiers(): LinkedModifiers {
return (
_composer.value ? _composer.value.modifiers : _modifiers
) as LinkedModifiers
},
get pluralRules(): PluralizationRules {
return (
_composer.value ? _composer.value.pluralRules : _pluralRules
) as PluralizationRules
},
get isGlobal(): boolean {
return _composer.value ? _composer.value.isGlobal : false
},
get missingWarn(): boolean | RegExp {
return _composer.value ? _composer.value.missingWarn : _missingWarn
},
set missingWarn(val: boolean | RegExp) {
if (_composer.value) {
_composer.value.missingWarn = val
}
},
get fallbackWarn(): boolean | RegExp {
return _composer.value ? _composer.value.fallbackWarn : _fallbackWarn
},
set fallbackWarn(val: boolean | RegExp) {
if (_composer.value) {
_composer.value.missingWarn = val
}
},
get fallbackRoot(): boolean {
return _composer.value ? _composer.value.fallbackRoot : _fallbackRoot
},
set fallbackRoot(val: boolean) {
if (_composer.value) {
_composer.value.fallbackRoot = val
}
},
get fallbackFormat(): boolean {
return _composer.value ? _composer.value.fallbackFormat : _fallbackFormat
},
set fallbackFormat(val: boolean) {
if (_composer.value) {
_composer.value.fallbackFormat = val
}
},
get warnHtmlMessage(): boolean {
return _composer.value
? _composer.value.warnHtmlMessage
: _warnHtmlMessage
},
set warnHtmlMessage(val: boolean) {
if (_composer.value) {
_composer.value.warnHtmlMessage = val
}
},
get escapeParameter(): boolean {
return _composer.value
? _composer.value.escapeParameter
: _escapeParameter
},
set escapeParameter(val: boolean) {
if (_composer.value) {
_composer.value.escapeParameter = val
}
},
t,
getPostTranslationHandler,
setPostTranslationHandler,
getMissingHandler,
setMissingHandler,
rt,
d,
n,
tm,
te,
getLocaleMessage,
setLocaleMessage,
mergeLocaleMessage,
getDateTimeFormat,
setDateTimeFormat,
mergeDateTimeFormat,
getNumberFormat,
setNumberFormat,
mergeNumberFormat
}
function sync(composer: Composer): void {
composer.locale.value = _locale.value
composer.fallbackLocale.value = _fallbackLocale.value
Object.keys(_messages.value).forEach(locale => {
composer.mergeLocaleMessage(locale, _messages.value[locale])
})
Object.keys(_datetimeFormats.value).forEach(locale => {
composer.mergeDateTimeFormat(locale, _datetimeFormats.value[locale])
})
Object.keys(_numberFormats.value).forEach(locale => {
composer.mergeNumberFormat(locale, _numberFormats.value[locale])
})
composer.escapeParameter = _escapeParameter
composer.fallbackFormat = _fallbackFormat
composer.fallbackRoot = _fallbackRoot
composer.fallbackWarn = _fallbackWarn
composer.missingWarn = _missingWarn
composer.warnHtmlMessage = _warnHtmlMessage
}
onBeforeMount(() => {
if (instance.proxy == null || instance.proxy.$i18n == null) {
throw createI18nError(I18nErrorCodes.NOT_AVAILABLE_COMPOSITION_IN_LEGACY)
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const composer = (_composer.value = (instance.proxy.$i18n as any)
.__composer as Composer)
if (scope === 'global') {
_locale.value = composer.locale.value
_fallbackLocale.value = composer.fallbackLocale.value
_messages.value = composer.messages.value
_datetimeFormats.value = composer.datetimeFormats.value
_numberFormats.value = composer.numberFormats.value
} else if (isLocale) {
sync(composer)
}
})
return wrapper as unknown as Composer
}