• Vue3封装全局插件


    定义一个全局加载组件

    一、首先定义dom元素

    定义一个index.vue文件

    1. <template>
    2. <div class="loading">
    3. loading...
    4. </div>
    5. </template>
    6. <script setup lang="ts">
    7. </script>
    8. <style scoped>
    9. .loading {
    10. display: flex;
    11. align-items: center;
    12. justify-content: center;
    13. font-size: 30px;
    14. color: #fff;
    15. background: rgba(0, 0, 0, 0.8);
    16. height: 100vh;
    17. }
    18. </style>

    第二步给dom元素添加,控制显示的开关和方法,然后通过defineExpose暴露出去

    1. <script setup lang="ts">
    2. import { ref } from "vue"
    3. const isShow = ref<boolean>(false);
    4. const show = () => {
    5. isShow.value = true
    6. }
    7. const hide = () => {
    8. isShow.value = false
    9. }
    10. defineExpose({
    11. isShow,
    12. show,
    13. hide
    14. })
    15. </script>
    二、把组件渲染到全局

    定义一个index.ts把组件暴露出去

    createVNode创建虚拟节点,render把节点渲染到body,然后创建一个全局变量方便操作$Loading

    1. import type { App, VNode } from "vue"
    2. import { createVNode, render } from 'vue'
    3. import loading from './index.vue'
    4. export default {
    5. install(app: App) {
    6. const Vnode: VNode = createVNode(loading);
    7. render(Vnode, document.body)
    8. app.config.globalProperties.$Loading = {
    9. show: Vnode.component?.exposed?.show,
    10. hide: Vnode.component?.exposed?.hide,
    11. }
    12. }
    13. }
    三、注册组件
    1. import { createApp } from 'vue'
    2. import App from './App.vue'
    3. import loading from './components/loading'
    4. const app = createApp(App)
    5. type Lod = {
    6. show():void,
    7. hide():void
    8. }
    9. declare module 'vue' {
    10. export interface ComponentCustomProperties {
    11. $Loading: Lod
    12. }
    13. }
    14. app.use(loading)
    15. app.mount('#app')

    使用

    1. <template>
    2. <div class="">
    3. </div>
    4. </template>
    5. <script setup lang="ts">
    6. import { getCurrentInstance } from 'vue';
    7. const app = getCurrentInstance();
    8. app?.proxy?.$Loading.show();
    9. setTimeout(() => {
    10. app?.proxy?.$Loading.hide();
    11. }, 2000)
    12. </script>
    13. <style scoped></style>

  • 相关阅读:
    认识C语言函数
    springboot疫情物资管理系统的设计与实现
    HTTP——
    main函数之前发生什么
    SLAM从入门到精通(里程计的计算)
    最新可编程射频设备带来的射频测试趋势
    23年下半年软考系统集成(中项)报名已开始!
    三天吃透MySQL面试八股文
    美团一面复活赛4/18
    Python离线翻译库argos-translate
  • 原文地址:https://blog.csdn.net/QAEARQ/article/details/134540056