Vue2 用Dialog 写一个弹窗组件

475 阅读1分钟

目标

  1. 简化弹窗流程
  2. 让弹窗在弹出时 其他地方无法操作
  3. 可以由父组件关闭弹窗

实现思路

使用 dialog 来达到 弹窗后其他地方无法点击

developer.mozilla.org/zh-CN/docs/…

然后通过ref来达到 父组件调用子组件方法

组件

<template>  
<div v-if="open" class="f-dialog">  
<dialog :id="id">  
<slot />  
</dialog>  
</div>  
</template>  
  
<script>  
export default {  
name: 'FDialog',  
props: {  
id: {  
type: String,  
default: 'dialog'  
},  
styleObject: {  
type: Object,  
default: () => {  
return {  
width: '100%',  
height: '100%'  
}  
}  
}  
},  
data() {  
return {  
open: true  
}  
},  
mounted() {  
const styleString = Object.keys(this.styleObject)  
.map(key => `${key}: ${this.styleObject[key]}`)  
.join('; ')  
const doc = document.getElementById(this.id)  
doc.setAttribute('style', styleString)  
doc.showModal()  
},  
methods: {  
closeDialog() {  
const doc = document.getElementById(this.id)  
doc.close()  
this.open = false  
}  
}  
}  
  
</script>  
  
<style>  
  
</style>

调用

<template>  
<div class="dashboard-container">  
<f-dialog id="dialogger" ref="child" :style-object="styleObject">  
<button @click="closeThis">关闭</button>  
</f-dialog>  
</div>  
</template>  
  
<script>  
import { mapGetters } from 'vuex'  
import FDialog from '@/components/Dialog/index.vue'  
  
export default {  
name: 'Dashboard',  
components: { FDialog },  
data() {  
return {  
styleObject: {  
width: '50%',  
height: '100%'  
}  
}  
},  
computed: {  
...mapGetters([  
'name'  
])  
},  
methods: {  
closeThis() {  
this.$refs.child.closeDialog()  
}  
}  
}  
</script>  
  
<style lang="scss" scoped>  
.dashboard {  
&-container {  
margin: 30px;  
}  
  
&-text {  
font-size: 30px;  
line-height: 46px;  
}  
}  
</style>