vue基于vant的popup组件封装confirm弹框
如果不是用vant组件库,推荐看:vue封装confirm弹框,通过transition设置动画
效果:
step:
1、components文件夹下新建MyConfirm文件夹,分别新建index.vue和index.js
index.vue:
<template> <div class="my-confirm"> <van-popup v-model="isShow"> <div class="con_box"> <h3>{{text.title}}</h3> <p>{{text.message}}</p> <div class="btn"> <van-button @click="handleClose()" v-if="text.btn.cancelText">{{text.btn.cancelText}}</van-button> <van-button @click="handleOk()" :loading='submitLoading' v-if="text.btn.okText">{{text.btn.okText}}</van-button> </div> </div> </van-popup> </div> </template> <script> export default { data() { return { submitLoading: false, // 每次创建弹框时loading状态都是false,所以在关闭时可以不用设置DOM.submitLoading = false isShow: true, text: { title: '提示', message: '确定删除此条信息?', btn: { okText: '确定', cancelText: '取消' } } } } } </script>
<style lang='less' scoped> .my-confirm { /deep/ .van-popup { border-radius: 10px; .con_box { width: 270px; line-height: 1; text-align: center; color: #4d5c82; padding: 25px 15px 15px; box-sizing: border-box; > h3 { font-size: 20px; } > p { font-size: 17px; margin-top: 15px; margin-bottom: 20px; line-height: 26px; } .btn { display: flex; justify-content: space-between; > .van-button { display: block; width: 114px; background-color: #e0e5f5; text-align: center; line-height: 44px; font-size: 17px; } > .van-button:last-of-type { background-color: #1288fe; color: #ffffff; } } } } } </style>
index.js:
import Vue from 'vue' import confirm from './index.vue' const constructor = Vue.extend(confirm) const myConfirm = function(text) { return new Promise((resolve, reject) => { const DOM = new constructor({ el: document.createElement('div') }) document.body.appendChild(DOM.$el) // new一个对象,然后插入body里面 DOM.text = text // 为了使confirm的扩展性更强,这个采用对象的方式传入,所有的字段都可以根据需求自定义 DOM.handleOk = function() { DOM.submitLoading = true // 打开确定按钮loading状态 resolve() DOM.isShow = false } DOM.handleClose = function() { reject() DOM.isShow = false } }) } export default myConfirm
2、main.js中引入并注册
// 引入自定义的 confirm 弹框
import myConfirm from './components/MyConfirm/index.js'
Vue.prototype.$confirm = myConfirm
3、使用
this.$confirm({
title: '提示',
message: '确认删除此篇周计划吗?',
btn: {
okText: '确定',
cancelText: '取消'
}
})
.then(() => {
// do something
})
.catch(() => {
console.log('no')
})