Vue使用Promise自定义confirm确认框组件

vue

使用Promise模拟浏览器确认框,可自定义标题,内容,按钮文字和类型

参数名类型说明
titleString标题
contentString内容
yesBtnTextString确认按钮文字,默认‘确定’
cancelBtnTextString取消按钮文字,默认‘取消’
typeStringinfo/success/warning/error,默认‘’

Confirm.vue

<template>

<transition name="fade">

<div class="confirm-wrap" v-if="visible">

<div class="confirm">

<div class="hd">

{{title}}

<i class="btn-close iconfont icon-close" @click="handleAction('close')"></i>

</div>

<div class="bd">

<i v-if="type!=''" class="icon-type iconfont" :class="'icon-'+type"></i>{{content}}

</div>

<div class="ft">

<a href="javscript:void(0)" class="btn btn-primary" @click="handleAction('yes')">{{yesBtnText}}</a>

<a href="javscript:void(0)" class="btn btn-default" @click="handleAction('cancel')">{{cancelBtnText}}</a>

</div>

</div>

<div class="backdrop" @click="handleAction('close')"></div>

</div>

</transition>

</template>

<script>

export default {

name: "MyConfirm",

data() {

return {

visible:false,

title:'',

content:'',

yesBtnText:'确定',

cancelBtnText:'取消',

type:'',

promiseStatus:null,

}

},

watch:{

visible:function(curVal) {

if(curVal&&document.body.scrollHeight > window.innerHeight){

$('body').addClass('backdrop-open');

}else{

$('body').removeClass('backdrop-open');

}

}

},

methods: {

confirm() {

let _this = this;

this.visible = true;

return new Promise(function (resolve, reject) {

_this.promiseStatus = {resolve, reject};

});

},

handleAction(action){

this.visible=false;

if(action=='yes'){

this.promiseStatus && this.promiseStatus.resolve();

}else{

this.promiseStatus && this.promiseStatus.reject();

}

}

}

}

</script>

index.js

import Vue from 'vue'

import Confirm from './Confirm.vue'

const ConfirmBox = Vue.extend(Confirm);

Confirm.install = (content, title, options) => {

if (typeof title === 'object') {

options = title;

title = '';

} else if (title === undefined) {

title = '';

}

options = Object.assign({

title: title,

content: content,

}, options);

let instance = new ConfirmBox({

data: options

}).$mount();

document.body.appendChild(instance.$el);

return instance.confirm();

};

export default Confirm

main.js

import Confirm from '@/components/common/Confirm'

Vue.prototype.$my_confirm = Confirm.install;

页面调用

show(){

this.$my_confirm('是否登录?',{

yesBtnText:'登录',

}).then(() => {

//点登录

}).catch(() => {

//点取消

});

},

show1(){

this.$my_confirm('此操作将永久删除该文件, 是否继续?','提示',{

yesBtnText:'是',

cancelBtnText:'否',

type: 'warning'

}).then(() => {

//点是

}).catch(() => {

//点否

});

},

效果图:

以上是 Vue使用Promise自定义confirm确认框组件 的全部内容, 来源链接: utcz.com/z/375440.html

回到顶部