vue3 h函数 进阶用法
默认我们放到body中就可以了 如果想放在某个div下 把div传过来就好了
props:就相当于父传子的数据
import {
render, h } from 'vue';
import showLoading from '../components/showLoading/src/index.vue';
export const showLoading = (props: any,dom) => {
const handleDestroy = () => {
// 从 body 上移除组件
render(null, dom || document.body);
};
const vnode = h(showLoading, {
...props, destroy: handleDestroy });
// 使用 render 函数将 vnode 渲染为真实DOM并挂载到 body 上
render(vnode, dom || document.body);
};
export const hideLoading = (props: any) => {
render(null, dom || document.body);
};
使用:
import {
showLoading, hideLoading } from './lib/showLoading';
showLoading({
message: '加载中...',
color: '#fff',
size: '30',
});
//关闭
hideLoading();
下面是部分的页面代码
<template>
<div class="xxx-loading-mark" v-if="isVisable">
<xxx-loading :color="color || '#fff'" :type="type" :size="size" :textSize="textSize" :textColor="textColor" :vertical="vertical">
{
{ message }}
</xxx-loading>
</div>
</template>
<script setup lang="ts">
import xxxLoading from '../../xxxLoading';
import {
onMounted, defineProps, ref } from 'vue';
const props = defineProps({
/** 颜色 */
color: {
type: String,
defalut: '#fff',
},
/** loading文案 */
message: {
type: [String, Number],
defalut: '',
},
/** 是否设置自动关闭时间 */
duration: {
type: Number,
defalut: 3000,
},
destroy: {
type: Function,
},
});
const isVisable = ref(true);
// 控制显示处理
onMounted(() => {
if (props.duration) {
setTimeout(() => {
isVisable.value = false;
props.destroy && props.destroy();
}, props.duration);
}
});
</script>
<script lang="ts">
export default {
name: 'ShowLoading',
};
</script>
<style lang="scss" scoped>
.xxx-loading-mark {
width: 100%;
height: 100%;
position: fixed;
top: 0;
left: 0;
display: flex;
align-items: center;
justify-content: center;
background: rgba(0, 0, 0, 0.3);
color: #fff;
}
</style>
注:由于之前是搭建的组件库 示例代码当作参考 其实组件就跟我们平常写组件一样就可以了