vue实现新增弹窗窗口
实现新增弹窗窗口的基本步骤
在Vue中实现新增弹窗窗口,可以通过组件化方式完成。弹窗通常包含一个触发按钮和一个模态框组件。
创建弹窗组件Modal.vue:
<template>
<div class="modal" v-if="show">
<div class="modal-content">
<span class="close" @click="closeModal">×</span>
<slot></slot>
</div>
</div>
</template>
<script>
export default {
props: {
show: {
type: Boolean,
default: false
}
},
methods: {
closeModal() {
this.$emit('close')
}
}
}
</script>
<style>
.modal {
position: fixed;
z-index: 1;
left: 0;
top: 0;
width: 100%;
height: 100%;
background-color: rgba(0,0,0,0.4);
}
.modal-content {
background-color: #fefefe;
margin: 15% auto;
padding: 20px;
border: 1px solid #888;
width: 80%;
}
.close {
color: #aaa;
float: right;
font-size: 28px;
font-weight: bold;
cursor: pointer;
}
</style>
在父组件中使用弹窗
在需要使用弹窗的父组件中,导入并注册Modal组件,然后通过数据控制弹窗显示。
<template>
<div>
<button @click="showModal = true">新增</button>
<Modal :show="showModal" @close="showModal = false">
<h3>新增内容</h3>
<!-- 表单内容 -->
<form>
<input type="text" placeholder="输入内容">
<button type="submit">提交</button>
</form>
</Modal>
</div>
</template>
<script>
import Modal from './Modal.vue'
export default {
components: {
Modal
},
data() {
return {
showModal: false
}
}
}
</script>
使用第三方UI库实现
如果项目中使用Element UI等第三方库,可以更简单地实现弹窗功能。
安装Element UI:
npm install element-ui
使用Element UI的Dialog组件:
<template>
<div>
<el-button type="primary" @click="dialogVisible = true">新增</el-button>
<el-dialog
title="新增内容"
:visible.sync="dialogVisible"
width="30%">
<!-- 表单内容 -->
<el-form>
<el-form-item label="名称">
<el-input v-model="form.name"></el-input>
</el-form-item>
</el-form>
<span slot="footer">
<el-button @click="dialogVisible = false">取消</el-button>
<el-button type="primary" @click="submitForm">确定</el-button>
</span>
</el-dialog>
</div>
</template>
<script>
export default {
data() {
return {
dialogVisible: false,
form: {
name: ''
}
}
},
methods: {
submitForm() {
// 提交逻辑
this.dialogVisible = false
}
}
}
</script>
弹窗动画效果
为弹窗添加过渡动画可以提升用户体验。在自定义弹窗组件中,可以使用Vue的transition组件。
修改Modal.vue:
<template>
<transition name="modal">
<div class="modal" v-if="show">
<div class="modal-content">
<span class="close" @click="closeModal">×</span>
<slot></slot>
</div>
</div>
</transition>
</template>
<style>
.modal-enter-active, .modal-leave-active {
transition: opacity .3s;
}
.modal-enter, .modal-leave-to {
opacity: 0;
}
</style>
弹窗表单验证
在弹窗中实现表单验证是常见需求。可以使用VeeValidate或Element UI内置的表单验证。
使用VeeValidate示例:
<template>
<Modal :show="showModal" @close="showModal = false">
<form @submit.prevent="submit">
<input v-model="name" v-validate="'required'" name="name">
<span v-show="errors.has('name')">{{ errors.first('name') }}</span>
<button type="submit">提交</button>
</form>
</Modal>
</template>
<script>
import { Validator } from 'vee-validate'
export default {
data() {
return {
name: '',
showModal: false
}
},
methods: {
submit() {
this.$validator.validateAll().then(result => {
if (result) {
// 验证通过
this.showModal = false
}
})
}
}
}
</script>






