一、Vue3混合插件开发
为了演示插件开发过程,这里创建一个简单弹窗组件。功能: 通过增加全局函数方法,使用渲染函数去调用Vue组件并挂载到真实DOM显示。
1. 文件目录
2. 创建弹窗组件 ,路径 /src/plugins/example/dialog.vue,这里仅供参考
// /src/plugins/example/dialog.vue
<script lang="jsx">
export default {
props: {
show: {
type: Boolean,
default: false
}
},
setup(props) {
const msg = '这里是弹窗内容,仅做演示'
return () =>
props.show ? (
<div className="dialog">
<div className="content">{msg}</div>
</div>
) : (
<div />
)
}
}
</script>
<style lang="scss" scoped>
.dialog {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
display: flex;
align-items: center;
justify-content: center;
background: black;
.content {
height: 100px;
width: 100%;
background: white;
margin: 0 30px;
padding: 15px;
border-radius: 10px;
}
}
</style>
3. 创建全局调用方法,路径 /src/plugins/example/index.js
// /src/plugins/example/index.js
import { h, render } from 'vue'
import Dialog from './dialog.vue'
const examplePlugin = {}
const removeElement = (el) => {
if (typeof el.remove !== 'undefined') {
el.remove()
} else {
el.parentNode.removeChild(el)
}
}
examplePlugin.install = function (app) {
app.config.globalProperties.$exampleDialog = (type) => {
if (typeof app.exampleDialogIns === 'undefined') { //创建弹窗
const obj = {
vNodes: h(Dialog, { show: type }), // 创建虚拟DOM
el: document.createElement('div') // 元素容器
}
render(obj.vNodes, obj.el) // 挂载到容器
document.body.appendChild(obj.el) // 追加到页面
app.exampleDialogIns = obj
}
if (!type) { // false则关闭弹窗并销毁变量
render(null, app.exampleDialogIns.el)
removeElement(app.exampleDialogIns.el)
delete app.exampleDialogIns
}
}
}
export default examplePlugin
二、插件使用
1. 入口导入插件 ,路径 /src/main.ts
// /src/main.ts
...
import exampleDialog from './plugins/example/index'
app.use(exampleDialog)
...
2. 组件里使用插件
<script setup lang="ts">
import { getCurrentInstance } from 'vue'
const ctx = getCurrentInstance()?.appContext.config.globalProperties
ctx.$exampleDialog(true)
setTimeout(() => ctx.$exampleDialog(false), 3000)
</script>
<template>
<div></div>
</template>