共计 1258 个字符,预计需要花费 4 分钟才能阅读完成。
实现一个简略的弹窗组件:
- vue2 函数式组件写法,通过
extend
办法:
创立ui.vue
文件,寄存咱们的组件,如下:
<template>
<div class="dialog">
<div class="dialog-body">
<div class="dialog-content">
你好
</div>
<div class="dialog-footer" @click="close"> 敞开 </div>
</div>
</div>
</template>
<script></script>
<style lang="scss" scoped>
.dialog {
width: 100vw;
height: 100vh;
position: fixed;
top: 0;
left: 0;
background-color: rgba($color: #000000, $alpha: 0.2);
&-body {
width: 500px;
height: 300px;
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
background-color: #fff;
border-radius: 4px;
padding: 10px;
}
&-content {height: 250px;}
&-footer {height: 50px;}
}
</style>
同级目录下创立一个 index.js,内容如下;
import UI from "./ui.vue"
import Vue from "vue"
function openDialog() {
let install = null
return new Promise((resolve, reject) => {const UIconstructor = Vue.extend(UI)
install = new UIconstructor({
methods: {close(e) {document.body.removeChild(install.$el)
resolve(e)
},
},
}).$mount();
document.body.appendChild(install.$el)
})
}
export default openDialog
在其余页面间接引入调用 openDialog
即可
- vue3 中实现,ui.vue 不变,index.js 批改如下:
import UI from "./ui.vue"
import {createApp} from "vue"
export default function openDialog() {
// 创立一个节点,并将组件挂载下来
const mountNode = document.createElement("div")
document.body.appendChild(mountNode)
const app: any = createApp(UI, {close: () => {app.unmount()
document.body.removeChild(mountNode)
},
})
app.mount(mountNode)
}
正文完