页面结构
<template>
<div class="page" @click.stop v-show="setShow">
<div class="loading">
加载中...
</div>
</div>
</template>
<script>
import { ref } from "vue";
export default {
name: "loading",
setup() {
const setShow = ref(false);
const show = () => {
setShow.value = true;
};
const hide = () => {
setShow.value = false;
};
setTimeout(() => {
//setShow.value = false;
}, 5000);
return {
setShow,
show,
hide,
};
},
};
</script>
<style scoped>
.page {
position: fixed;
width: 100vw;
height: 100vh;
display: flex;
align-items: center;
justify-content: center;
top: 0;
left: 0;
z-index: 999;
}
.loading {
display: flex;
align-items: center;
justify-content: center;
width: 30vw;
height: 30vw;
background: rgba(0, 0, 0, 0.7);
border-radius: 6px;
}
</style>
js,createVNode创建,globalProperties配置
// loading.js
import { createVNode, render } from 'vue'
import LoadingComponent from './loading.vue'
let $data;
export default {
install: (app) => {
if (!$data) {
// LoadingComponent 为自己写的组件
$data = createVNode(LoadingComponent, {}, {
default: () => createVNode()
});
$data.appContext = app._context; // 这句很关键,关联起了数据
render($data, document.body);
}
$data.component.ctx.setShow = false;
let loading = {
show() {
$data.component.ctx.show();
},
hide() {
$data.component.ctx.hide();
}
};
if (!app.$loading) {
app.$loading = loading;
}
app.config.globalProperties.$loading = app.$loading;
}
}
引入
import { createApp } from 'vue'
import App from './App.vue'
import loading from './components/loding/loading'
const app = createApp(App);
app.use(loading);//自定义的加载中loading
app.mount('#app')
调用
import { getCurrentInstance } from "vue";
export default {
loading() {
const instance = getCurrentInstance();
instance.proxy.$loading.show();
},
}