vue2封装一个弹出框组件

封装一个弹出框组件,类似于element中的messageBox

vue样式组件

<template>
	<div class="message_page" v-show="isShow" @click="otherClick" ref="confirmBox">
		<p>{{title}}</p>
		<p>{{content}}</p>
		<div class="btn">
			<button type="button" @click="confirm">{{btn1}}</button>
			<button type="button" @click="cancel">{{btn2}}</button>
		</div>
	</div>
</template>
<script>
export default{
	props:{
		title:{
			type:String,
			default:'提示'
		},
		content:{
			type:String,
			default:'确认退出登录吗'
		},
		confirmBtn:{
			type:String,
			default:'确认'
		},
		cancelBtn:{
			type:String,
			default:'取消'
		}
	},
	data(){
		return {
			isShow:false,
			promiseStatus:null
		}
	},
	methods:{
		initMessageBox(){
				let _this = this
				this.show = true
				return new Promise(function(resolve,reject){
					_this.promiseStatus = {resolve,reject}
			})
		}
		otherClick(){
			// 点击其他区域隐藏弹出框
			let confirmBox = this.$refs.confirmBox
			if(e.target.contains(confirmBox)){
					this.cancel()
			}
		},
		cancel(){
			this.show = false
			this.promiseStatus&&this.promiseStatus.reject()
		},
		confirm(){
			this.show = false
			setTimeOut(()=>{
				this.show = false
			},300)
			this.promiseStatus&&this.promiseStatus.resolve()
		}
	}
}
</script>
<style>
// 样式
</style>

创建index.js文件

import Vue from 'vue'
Import Message from './message'
const MessageComponent = Vue.extend(Message)
const vm = new MessageComponent().$mount()
let init = false
const message = function(){
	Object.assign(vm,option,{
		type:'confirm'
})
if(!init){
	document.body.appendChild(vm.$el)
	init = true
	}
	return vm.initMessageBox()
}
export default message

在main.js中全局引入

import MessageBox from './index.js'
Vue.prototype.$Message = MessageBox
接下来就可以全局中使用$Message 调用组件了

例如

this.$Message({title:'警告',content:'请先登录'}).then(()=>{
			// 处理确认后的逻辑事件
		}).catch((err)=>{console.log(err})
  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值