varlet库loading组件模版使用转函数式调用方法
2024年5月8日10:34:19
varlet库loading组件模版使用转函数式调用方法
鉴于在H5中varlet.Snackbar在axios请求封装函数中总是会产生阻塞现象问题,而varlet.loading又不能函数式调用。
// loading.vue
<script lang="ts" setup>
import { ref, onMounted } from 'vue'
import { useWindowSize } from '@vueuse/core'
import { omit } from 'lodash-es'
import type { LoadingProps } from '@varlet/ui/types/loading'
type customPropType = {
init: Function
}
const { height } = useWindowSize()
const props = defineProps<LoadingProps & customPropType>()
const loading = ref<boolean>(false)
onMounted(() => {
props?.init(instance)
})
function start() {
loading.value = true
}
function finish() {
loading.value = false
}
const instance = {
start,
finish
}
defineExpose(instance)
</script>
<template>
<var-overlay :show="loading">
<div class="w-screen flex flex-col justify-center items-center" :style="{ height: height + 'px' }">
<var-loading v-bind="{ ...omit(props, ['loading']) }" :loading="loading"></var-loading>
</div>
</var-overlay>
</template>
<style lang="scss" scoped></style>
// loading.ts
import { render, h } from "vue";
import Loading from "./loading.vue";
import type { LoadingProps } from '@varlet/ui/types/loading'
export const RenderLoading = (options: LoadingProps) => {
let instance: any
const divElement = document.createElement('div')
rendering(divElement)
document.body.appendChild(divElement)
function renderVNode() {
const vNode = h(Loading, { ...options, init: (i: any) => { instance = i } })
return vNode
}
function rendering(container: Element) {
render(renderVNode(), container)
}
return instance
}
export default RenderLoading
使用方式
// 函数式调用
const load = RenderLoading({ description: 'LOADING' })
load.start()
load.finish()
// 当然也保留了原先模版调用方式