30-编写Vue3插件

Huxzhi大约 2 分钟vue3

插件

插件是自包含的代码,通常向 Vue 添加全局级功能。29-Vue3定义全局函数和变量

你如果是一个对象需要有 install 方法 Vue 会帮你自动注入到 install 方法 你如果是 function 就直接当 install 方法去使用

使用插件

在使用 createApp() 初始化 Vue 应用程序后,你可以通过调用 use() 方法将插件添加到你的应用程序中。

实现一个 Loading

Loading/index.vue

<template>
  <div v-if="isShow" class="loading">
    <div class="loading-content">Loading...</div>
  </div>
</template>
  
<script setup lang='ts'>
import { ref } from 'vue';
const isShow = ref(false)//定位loading 的开关

const show = () => {
  isShow.value = true
}
const hide = () => {
  isShow.value = false
}
//对外暴露 当前组件的属性和方法
defineExpose({
  isShow,
  show,
  hide
})
</script>
  
<style scoped lang="less">
.loading {
  position: fixed;
  inset: 0;
  background: rgba(0, 0, 0, 0.8);
  display: flex;
  justify-content: center;
  align-items: center;

  &-content {
    font-size: 30px;
    color: #fff;
  }
}
</style>

Loading/index.ts

import { createVNode, render, VNode, App } from 'vue';
import Loading from './index.vue'

export default {
  //组件被 use 之后自动执行里面的 install 方法
  install(app: App) {
    //createVNode vue提供的底层方法 可以给我们组件创建一个虚拟DOM 也就是Vnode
    const vnode: VNode = createVNode(Loading)
    //render 把我们的Vnode 生成真实DOM 并且挂载到指定节点
    render(vnode, document.body)
    // Vue 提供的全局配置 可以自定义
    app.config.globalProperties.$loading = {
      show: () => vnode.component?.exposed?.show(),
      hide: () => vnode.component?.exposed?.hide()
    }

  }
}

main.ts

import { createApp } from 'vue'
// import './style.css'
import App from './App.vue'
import './assets/css/reset.less'
import Layout from './layout/index.vue'
import loading from './components/loading'


let app = createApp(App)

app.use(loading)


type Lod = {
  show: () => void,
  hide: () => void
}
//编写ts loading 声明文件放置报错 和 智能提示
declare module '@vue/runtime-core' {
  export interface ComponentCustomProperties {
    $loading: Lod
  }
}



app.mount('#app')

App.vue

<template>

  <div></div>

</template>
 
<script setup lang='ts'>
import { ref, reactive, getCurrentInstance } from 'vue'
const instance = getCurrentInstance()
instance?.proxy?.$loading.show()
setTimeout(() => {
  instance?.proxy?.$loading.hide()
}, 5000)


// console.log(instance)
</script>
<style>
* {
  padding: 0;
  margin: 0;
}
</style>