vue基于vant的popup组件封装confirm弹框

如果不是用vant组件库,推荐看:vue封装confirm弹框,通过transition设置动画

效果:

step:

1、components文件夹下新建MyConfirm文件夹,分别新建index.vue和index.js

  index.vue:

<template>
  <van-popup v-model="isShow">
    <div class="con_box">
      <h3>{{text.title}}</h3>
      <p>{{text.message}}</p>
      <div class="btn">
        <span @click="handleClose()" v-if="text.btn.cancelText">{{text.btn.cancelText}}</span>
        <span @click="handleOk()" v-if="text.btn.okText">{{text.btn.okText}}</span>
      </div>
    </div>
  </van-popup>
</template>
<script>
export default {
  data() {
    return {
      isShow: true,
      text: {
        title: '提示',
        message: '确定删除此条信息?',
        btn: {
          okText: '确定',
          cancelText: '取消'
        }
      }
    }
  },
  methods: {
    handleClose() {
      console.log('关闭')
    },
    handleOk() {
      console.log('确定')
    }
  }
}
</script>
<style lang='less' scoped>
.van-popup {
  border-radius: 10px;
  .con_box {
    width: 270px;
    line-height: 1;
    text-align: center;
    color: #4d5c82;
    padding: 15px;
    box-sizing: border-box;
    > h3 {
      font-size: 20px;
      margin-top: 10px;
      margin-bottom: 20px;
    }
    > p {
      font-size: 17px;
      margin-bottom: 30px;
    }
    .btn {
      display: flex;
      justify-content: space-between;
      > span {
        display: block;
        width: 114px;
        background-color: #e0e5f5;
        text-align: center;
        line-height: 44px;
        font-size: 17px;
      }
      > span:last-of-type {
        background-color: #1288fe;
        color: #ffffff;
      }
    }
  }
}
</style>

  index.js:

import Vue from 'vue'
import confirm from './index.vue'
let confirmConstructor = Vue.extend(confirm)
let myConfirm = function (text) {
  return new Promise((resolve, reject) => {
    let confirmDom = new confirmConstructor({
      el: document.createElement('div')
    })
    document.body.appendChild(confirmDom.$el) // new一个对象,然后插入body里面
    confirmDom.text = text // 为了使confirm的扩展性更强,这个采用对象的方式传入,所有的字段都可以根据需求自定义
    confirmDom.handleOk = function () {
      resolve()
      confirmDom.isShow = false
    }
    confirmDom.handleClose = function () {
      reject()
      confirmDom.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') })
原文地址:https://www.cnblogs.com/wuqilang/p/14869134.html