Vue 弹窗组件:简单易用,功能丰富 | 示例代码
Vue 弹窗组件是一种方便用户进行交互操作的组件,通常用于展示提示、警告、确认等信息,以及获取用户输入。Vue 弹窗组件可以通过自定义样式、内容、事件等属性来满足不同场景的需求。
以下是一个简单的 Vue 弹窗组件示例:
<template>
<div class='modal' v-if='show'>
<div class='modal-content'>
<div class='modal-header'>
<h3>{{ title }}</h3>
<i class='fa fa-close' @click='closeModal'></i>
</div>
<div class='modal-body'>
{{ message }}
</div>
<div class='modal-footer'>
<button class='btn btn-primary' @click='confirm'>确认</button>
<button class='btn btn-default' @click='cancel'>取消</button>
</div>
</div>
</div>
</template>
<script>
export default {
props: {
title: String,
message: String,
show: Boolean,
},
methods: {
closeModal() {
this.$emit('close');
},
confirm() {
this.$emit('confirm');
},
cancel() {
this.$emit('cancel');
},
},
};
</script>
<style scoped>
.modal {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.6);
z-index: 999;
}
.modal-content {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background-color: #fff;
padding: 20px;
}
.modal-header {
display: flex;
justify-content: space-between;
}
.modal-header h3 {
margin: 0;
font-size: 16px;
}
.modal-header i {
cursor: pointer;
}
.modal-body {
margin: 20px 0;
}
.modal-footer {
display: flex;
justify-content: flex-end;
}
.btn {
padding: 5px 10px;
border: none;
border-radius: 3px;
cursor: pointer;
}
.btn-primary {
background-color: #007bff;
color: #fff;
}
.btn-default {
background-color: #f1f1f1;
color: #333;
margin-left: 10px;
}
</style>
在父组件中,可以通过以下方式使用该弹窗组件:
<template>
<div>
<button @click='showModal'>打开弹窗</button>
<modal :title='title' :message='message' :show='isModalVisible' @close='closeModal' @confirm='confirmModal' @cancel='cancelModal'></modal>
</div>
</template>
<script>
import Modal from './Modal.vue';
export default {
components: {
Modal,
},
data() {
return {
title: '提示',
message: '确定要执行此操作吗?',
isModalVisible: false,
};
},
methods: {
showModal() {
this.isModalVisible = true;
},
closeModal() {
this.isModalVisible = false;
},
confirmModal() {
// 确认操作
this.isModalVisible = false;
},
cancelModal() {
// 取消操作
this.isModalVisible = false;
},
},
};
</script>
在上述代码中,通过引用 Modal 组件,并传递 title、message、show 等属性,来展示弹窗。同时,定义了 close、confirm、cancel 等事件,用于响应用户的操作。
原文地址: https://www.cveoy.top/t/topic/n51d 著作权归作者所有。请勿转载和采集!