实现一个 Modal 可以使用 Vue3.0 中的组合式 API。
首先,我们可以创建一个 Modal 组件,包含以下结构:
<template>
<div class="modal-wrapper" v-show="visible">
<div class="modal-mask" @click.self="close"></div>
<div class="modal">
<div class="modal-header">
<h3>{{ title }}</h3>
<button @click="close">×</button>
</div>
<div class="modal-body">
<slot></slot>
</div>
</div>
</div>
</template>
在 setup 函数中,我们可以使用 ref 创建一个可响应的 visible 变量,并提供 open 和 close 方法以打开和关闭 Modal:
<script>
import { ref } from 'vue'
export default {
props: {
title: {
type: String,
required: true
}
},
setup(props, { emit }) {
const visible = ref(false)
const open = () => {
visible.value = true
}
const close = () => {
visible.value = false
emit('update:visible', false)
}
return {
visible,
open,
close
}
}
}
</script>
在父组件中,可以通过 v-model 绑定 visible 变量来打开或关闭 Modal。同时,我们也可以在 Modal 组件中通过 $emit 来发送一个自定义的事件,如 close 事件,以在父组件中监听关闭 Modal 的操作。
<template>
<div>
<button @click="openModal">打开 Modal</button>
<Modal v-model:visible="modalVisible" title="这是 Modal 标题" @close="modalVisible = false">
<p>这是 Modal 内容</p>
</Modal>
</div>
</template>
<script>
import Modal from './Modal.vue'
export default {
components: {
Modal
},
data() {
return {
modalVisible: false
}
},
methods: {
openModal() {
this.modalVisible = true
}
}
}
</script>
这样,我们就成功地实现了一个简单的 Modal,可以通过在父组件中设置 Modal 的 title 和内容来创建不同的 Modal。