vue 封装一个通用弹框组件
以下是一个简单的 Vue 弹框组件示例:
<template>
<div class="modal" v-if="visible">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">{{ title }}</h5>
<button type="button" class="close" @click="closeModal">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<slot></slot>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" @click="closeModal">
{{ cancelText }}
</button>
<button type="button" class="btn btn-primary" @click="confirm">
{{ confirmText }}
</button>
</div>
</div>
</div>
</div>
</template>
<script>
export default {
name: "Modal",
props: {
title: {
type: String,
default: "提示",
},
visible: {
type: Boolean,
default: false,
},
confirmText: {
type: String,
default: "确定",
},
cancelText: {
type: String,
default: "取消",
},
},
methods: {
closeModal() {
this.$emit("update:visible", false);
},
confirm() {
this.$emit("confirm");
},
},
};
</script>
这个组件接受以下 props:
title:弹框标题,默认为“提示”。visible:控制弹框是否显示,默认为false。confirmText:确定按钮文本,默认为“确定”。cancelText:取消按钮文本,默认为“取消”。
该组件包含一个插槽,可以在弹框中渲染任意内容。它还触发两个事件:
update:visible:当用户关闭弹框时,该事件会触发,将visible属性设置为false。confirm:当用户点击确定按钮时,该事件会触发。
你可以像这样在父组件中使用它:
<template>
<div>
<button @click="showModal = true">打开弹框</button>
<modal :visible.sync="showModal" @confirm="handleConfirm">
<p>这里是弹框内容</p>
</modal>
</div>
</template>
<script>
import Modal from "./Modal.vue";
export default {
name: "App",
components: {
Modal,
},
data() {
return {
showModal: false,
};
},
methods: {
handleConfirm() {
console.log("用户点击了确定按钮");
},
},
};
</script>
在这个例子中,我们使用了一个showModal属性来控制弹框的显示。当用户点击“打开弹框”按钮时,我们将showModal设置为true,这将显示弹框。我们还使用了.sync修饰符将visible属性绑定到showModal,这意味着当用户关闭弹框时,showModal会自动更新为false,而不需要手动更新。
当用户点击“确定”按钮时,handleConfirm方法会被调用。你可以在这个方法中执行任何你想要的操作,比如向服务器发送请求或者更新页面内容。
这个弹框组件只是一个基础示例,你可以根据自己的需求进行扩展和定制
原文地址: https://www.cveoy.top/t/topic/egYj 著作权归作者所有。请勿转载和采集!