如果不是用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')
})