封装onLoad
import { getCurrentInstance } from '@vue/composition-api'
export function onLoad(callback: (options: Record<string, string | undefined>) => void) {
getCurrentInstance()?.proxy.$on('hook:onLoad', callback)
}
export function onShow(callback: () => void) {
const $this = getCurrentInstance()?.proxy
if ($this) {
const hook = $this.$mp.page ? 'onShow' : 'onPageShow'
$this.$on(`hook:${hook}`, callback)
}
}
封装哪些hook就在全局混入里加入哪些hook, 否则自己封装的hook可能不会触发
import Vue from 'vue'
import { noop } from 'lodash'
Vue.mixin({
onLoad: noop,
onShow: noop
})
封装template ref
import Vue, { ComponentOptions } from 'vue'
import { CombinedVueInstance } from 'vue/types/vue'
import { getCurrentInstance, onMounted, onUpdated, Ref, ref } from '@vue/composition-api'
type VueInstance = Vue extends {$refs: { [key: string]: infer R }} ? R : never
type CombinedVueInstanceFromOptions<
Options extends ComponentOptions<Vue>,
> = Options extends ComponentOptions<
infer Vue,
infer Data,
infer Methods,
infer Computed,
{},
infer Props
> ? CombinedVueInstance<Vue, Data, Methods, Computed, Props> : never
/**
* @description 接收一个字符串返回对应的ref名称的组件实例
* @example
* setup() {
* //如果是class组件
* const input = useVueRef<Input>('refName')
* //如果是选项式组件
* const input = useVueRef<typeof Input>('refName')
*
* onMounted(() => input.value?.focus())
* }
* */
function useVueRef<
Instance extends ComponentOptions<Vue> | ComponentOptions<Vue>[] | VueInstance = VueInstance,
VueRef = Instance extends VueInstance ? Instance :
Instance extends ComponentOptions<Vue>[] ? CombinedVueInstanceFromOptions<Instance[number]>[] :
Instance extends ComponentOptions<Vue> ? CombinedVueInstanceFromOptions<Instance> :
never
>(refName: string): Ref<VueRef | undefined> {
const $vm = getCurrentInstance()?.proxy
const vueRef = ref<VueRef | undefined>()
if ($vm) {
const refreshRef = () => {
vueRef.value = $vm.$refs[refName] as unknown as VueRef | undefined
}
onMounted(refreshRef)
onUpdated(refreshRef)
}
return vueRef
}
export default useVueRef