Vue弹窗组件的实现

弹窗组件包含内容:

  • 弹窗遮罩层
  • 内容层的实现(涉及slot、props、$on$emit

实现步骤:

  1. 搭建组件UI样式,HTML、css实现遮罩层、内容区
  2. 编写弹窗内容:通过组件slot插槽接收父组件传递过来的弹窗内容
  3. 组件开关的实现:通过父组件传递进来的props控制组件的显示与隐藏,子组件关闭时通过事件 $emit 触发父组件改变状态值。

组件代码实现

<template>
	<div class="modal-bg" v-show="show">
		<div class="modal-container">
			<div class="modal-header">
				{{title}}
			</div>
			<div class="modal-main">
				<!-- 
					如果有多个插槽时,可以采用具名插槽的方式实现
					<slot name="main"></slot>
				 -->
				<slot></slot>
			</div>
			<div class="modal-footer">
				<button @click="close">关 闭</button>
				<button @click="submit">确 定</button>
			</div>
		</div>
	</div>
</template>
<script>
export default{
	name: 'modal',
	data() {
		return {}	
	},
	props: {
		show: {    // 控制弹窗展示
			type: Boolean,
			default: false,	
			required: true,   // 必传递
		},
		title: {
			type: String,
			default: 'title',
		}
	},
	methods: {
		// 通过事件绑定及$emit来执行父组件的方法,改变弹窗展示状态
		close() {
			this.$emit("hideModal");	
		},
		submit() {
			this.$emit("submit");	
		}
	}
}
</script>
<style>
.modal-bg{
	position: fixed;
	top: 0;
	right: 0;
	bottom: 0;
	left: 0;
	display: flex;
	justify-content: center;
	align-items: center;
	background: rgba(0, 0, 0, .4);
	z-index:999;
}
.modal-container{
	border-radius: 8px;
	background: #fff;
}
.model-header{
	heigth: 60px;
	background: blue;
	color:#fff;
}
.modal-main {
	padding: 20px 40px;
}
.modal-footer{
	height: 60px;
	display: flex;
	justify-content: center;
	align-item: center;
	border-top: 1px solid #000;
}
.modal-footer button{
	width:100px;
}
</style>

父组件中调用:

<template>
	<div>
		<Modal :show="show" :title="title" @hideModal="hideModal" @submit="submit">
			<!-- 
				向 slot 插槽中展示的内容 
				具名传递: <div slot="main">我是具名插槽传递内容的</div>
			-->
			<div>我是slot中的内容</div>
		</Modal>
	</div>
</template>
<script>
import Modal from "./modal.vue";
export default {
	name: "parentVue",
	data() {
		return {
			show: false,
			title: "我是弹窗标题",
		}	
	},
	components: {
		Modal,
	},
	methods: {
		// 关闭弹窗
		hideModal() {
			this.show = false;
		}
		// 显示弹窗
		submit() {
			this.show = true;	
		}
	}
}
</script>
<style>

</style>

温馨提示:
目前的市面上,有很多现有的 UI 组件库,如Element-UI等,很少会直接编写UI样式代码之类的操作,可以直接使用第三方库完成项目需求。

  • 4
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值