注意:Vue 3 建议对组件中所有发出的事件 emit 进行记录 emits 。如果你声明了 emits 选项,并且发送的事件没有被 emits 记录,则会收到一个警告:
[Vue warn]: Component emitted event "update:showModel" but it is neither declared in the emits option nor as an "onUpdate:showModel" prop.
模态框组件代码:
<template>
<teleport to="body">
<div v-show="showModel">
<div class="mask" @click="$emit('update:showModel', false)"></div>
<div class="model">
<h1>{{title}}</h1>
<div class="content">
<slot></slot>
</div>
</div>
</div>
</teleport>
</template>
<script>
export default {
// 这里要保留,否则会报警告
emits: ['showModel'],
props:['showModel', 'title'],
}
</script>
<style scoped>
.mask{width: 100%; height: 100%; background-color: rgba(0, 0, 0, .2); position: fixed; top:0; left: 0;}
.model{position: absolute; width: 300px; height: 300px; transform: translate(-50%, -50%); z-index: 2; background: #fff; left: 50%; top:50%;}
.model h1{font-weight: normal; margin: 0; text-align: center; font-size: 18px; padding: 20px 0;}
.model .content{padding:10px 20px 20px; font-size: 14px;}
</style>
父组件调用模态框:
<template>
<button @click="showModel = true">弹出模态框</button>
<model v-model:showModel="showModel" :title="modelTitle">model内容</model>
</template>
<script>
import Model from './Model'
export default {
components:{
Model
},
data(){
return {
showModel: false,
modelTitle: 'model标题'
}
},
}
</script> 