Vue实现弹窗的方法有很多种,这里给出一个简单的示例:
1. 首先,在Vue项目中创建一个名为`Modal.vue`的组件文件:
```html
<template>
<div class="modal-mask" v-show="visible" @click.self="close">
<div class="modal-container">
<div class="modal-header">
<slot name="header">
默认标题
</slot>
</div>
<div class="modal-body">
<slot name="body">
默认内容
</slot>
</div>
<div class="modal-footer">
<slot name="footer">
<button @click="close">关闭</button>
</slot>
</div>
</div>
</div>
</template>
<script>
export default {
props: {
visible: {
type: Boolean,
default: false
}
},
methods: {
close() {
this.$emit('update:visible', false);
}
}
};
</script>
<style scoped>
.modal-mask {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.5);
display: flex;
justify-content: center;
align-items: center;
}
.modal-container {
background-color: #fff;
padding: 20px;
border-radius: 5px;
width: 50%;
}
</style>
```
2. 在需要使用弹窗的组件中引入`Modal.vue`,并在模板中使用:
```html
<template>
<div>
<button @click="showModal = true">打开弹窗</button>
<Modal :visible.sync="showModal">
<template #header>
自定义标题
</template>
<template #body>
自定义内容
</template>
<template #footer>
<button @click="showModal = false">关闭</button>
</template>
</Modal>
</div>
</template>
<script>
import Modal from './Modal.vue';
export default {
components: {
Modal
},
data() {
return {
showModal: false
};
}
};
</script>
```
这样,当点击“打开弹窗”按钮时,弹窗就会显示出来。点击弹窗外部区域或“关闭”按钮,弹窗会关闭。你可以根据需要自定义弹窗的标题、内容和底部操作按钮。
以下是常用的Vue弹窗实现代码:
1. 使用Element UI组件库的Dialog组件
```html
<template>
<el-button @click="dialogVisible = true">打开弹窗</el-button>
<el-dialog :visible.sync="dialogVisible" title="弹窗标题">
<p>弹窗内容</p>
<span slot="footer" class="dialog-footer">
<el-button @click="dialogVisible = false">取 消</el-button>
<el-button type="primary" @click="dialogVisible = false">确 定</el-button>
</span>
</el-dialog>
</template>
<script>
export default {
data() {
return {
dialogVisible: false
}
}
}
</script>
```
2. 使用Vue自定义组件实现弹窗
```html
<template>
<div>
<button @click="showModal">打开弹窗</button>
<modal :show="show" @close="closeModal">
<h2>弹窗标题</h2>
<p>弹窗内容</p>
<button @click="closeModal">关闭弹窗</button>
</modal>
</div>
</template>
<script>
import Modal from './Modal.vue'
export default {
components: {
Modal
},
data() {
return {
show: false
}
},
methods: {
showModal() {
this.show = true
},
closeModal() {
this.show = false
}
}
}
</script>
```
3. 使用Vue插件实现弹窗
```html
<template>
<div>
<button @click="showModal">打开弹窗</button>
</div>
</template>
<script>
import Vue from 'vue'
import MyDialog from './MyDialog.vue'
export default {
methods: {
showModal() {
const Dialog = Vue.extend(MyDialog)
const dialog = new Dialog({
el: document.createElement('div')
})
document.body.appendChild(dialog.$el)
}
}
}
</script>
```