vue3.0 loading 插件注册

页面结构

<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();
    },
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容