1、认识Vue插件
通常我们像vue全局添加一些功能时,会 采用插件 的模式,有以下两种写法。
- 对象类型:一个对象,但必须包含一个install函数,该函数会在安装插件时执行
- 函数类型:一个function,此函数会在安装插件时自动执行
插件可以实现添加 全局的方法或资源(过滤器、过渡)等等
2、插件的编写方式
2.1、对象类型写法
// plugins/plug_obj.ts
import { App } from 'vue'
export default {
install(app: App) {
app.config.globalProperties.$message = '全局message属性'
}
}
2.2、函数类型写法
// plugins/plug_fun.ts
import { App } from 'vue'
export default function(app: App) {
app.config.globalProperties.$age = '全局age属性'
}
3、引入及使用
3.1、main.ts中引入
import { createApp } from 'vue'
import App from './App.vue'
import plugObj from "./plugins/plug_obj"
import plugFun from "./plugins/plug_fun"
const app = createApp(App)
app.use(plugObj)
app.use(plugFun)
app.mount('#app')
3.2、其他组件中使用
<script setup lang="ts">
import { getCurrentInstance, ComponentInternalInstance } from 'vue'
const { appContext } = getCurrentInstance() as ComponentInternalInstance
console.log(appContext.config.globalProperties.$message)
</script>
4、Loading插件Demo
// 1、定义一个loading.vue组件
<template>
<div v-if="isShow" class="loading">
<div class="content">
loading
</div>
</div>
</template>
<script setup lang="ts">
import {ref} from 'vue'
const isShow = ref(false)
const show = () => {
isShow.value = true
}
const hide = () => {
isShow.value = false
}
defineExpose({
isShow,
show,
hide,
})
</script>
<style scoped>
.loading {
position: fixed;
left: 0;
top: 0;
width: 100vw;
height: 100vh;
background-color: rgba(0, 0, 0, .4);
display: flex;
align-items: center;
justify-content: center;
}
.content {
font-size: 28px;
color: #ecd6d6;
}
</style>
// 2、自定义loading.ts插件,添加全局方法------------------------------------------------------------------
import { App, VNode, createVNode, render } from 'vue'
import Loading from './loading.vue'
export default {
install(app: App) {
// vue提供的创建虚拟DOM方法(createVNode)
const vnode: VNode = createVNode(Loading)
// 将虚拟DOM生成真实的DOM并挂载到指定节点
render(vnode, document.body)
console.log(vnode)
// Vue全局中注册方法
app.config.globalProperties.$loading = {
show: vnode.component?.exposed?.show,
hide: vnode.component?.exposed?.hide,
}
}
}
// 3、在main.ts中引入这个插件-------------------------------------------------------------------------------
import { createApp } from 'vue'
import App from './App.vue'
import Loading from "./components/loading"
const app = createApp(App)
app.use(Loading)
app.mount('#app')
// 4、在其他组件中使用-------------------------------------------------------------------------------------
<template>
<div>
<button @click="change">切换</button>
</div>
</template>
<script setup lang="ts">
import { getCurrentInstance, ComponentInternalInstance } from 'vue'
const { appContext } = getCurrentInstance() as ComponentInternalInstance
const change = () => {
appContext.config.globalProperties.$loading.show()
setTimeout(() => {
appContext.config.globalProperties.$loading.hide()
}, 3000)
}
</script>
原文链接:
https://blog.csdn.net/qq_41880073/article/details/124271358
https://xiaoman.blog.csdn.net/article/details/123300264