vue的自定义alert插件

本文展示了如何创建一个名为mAlert的Vue组件,该组件用于弹出提示框,包含确认和取消按钮。组件接受配置对象,允许自定义提示信息和按钮文字。同时,mAlert.js文件中定义了一个安装方法,将mAlert集成到Vue应用中,通过Vue.prototype.$mAlert方法调用。在main.js中引入并使用,然后在实例中捕获用户点击确定或取消的响应。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

目录结构:
在这里插入图片描述
mAlert.vue的代码:

<template>
  <div id="mAlert" v-show="showAlert">
    <div class="box">
      <p>{{config.txt}}</p>
      <div>
        <span @click="ok()">{{config.okTxt || '确定'}}</span>
        <span @click="no()">{{config.noTxt || '取消'}}</span>
      </div>
    </div>
  </div>
</template>

<script>
  export default {
    name: "mAlert.vue",
    props: {
      config: {
        type: Object,
        default: function () {
          return {
            txt: '',
            okTxt: '确定',
            noTxt: '取消'
          }
        }
      }
    },
    data () {
      return {
        showAlert: false
      }
    },
  }
</script>

<style scoped>
  #mAlert{
    position: fixed;
    z-index: 999;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    background: rgba(0,0,0,0.7);
  }
  .box{
    width: 61.8%;
    border-radius: 10px;
    background: #fff;
    text-align: center;
    margin: 30% auto 0;
  }
  .box p{
    padding: 20px;
  }
  .box div{
    display: flex;
    border-top: 1px solid #ccc;
  }
  .box span{
    flex: 1;
    padding: 10px;
  }
  .box span:first-child{
    border-right: 1px solid #ccc;
    color: dodgerblue;
  }
</style>

mAlert.js的代码:

import mAlertDom from './mAlert.vue'
import Vue from 'vue'

let mAlert = {}

mAlert.install = function (Vue, options) {
  const constructor = Vue.extend(mAlertDom)
  const instance = new constructor()
  Vue.prototype.$mAlert = (config) => {
    return new Promise((resolve, reject) => {
      instance.config = config
      instance.showAlert = true
      instance.no = () => {
        instance.showAlert = false
        reject(false)
      }
      instance.ok = () => {
        instance.showAlert = false
        resolve(true)
      }
    })
  }
  instance.$mount(document.createElement('div'))
  document.body.appendChild(instance.$el)
}
export default mAlert

main.js引入并use:

import mAlert from "./plugin/mAlert/mAlert.js"
Vue.use(mAlert)

调用:

this.$mAlert({txt: '又在写bug?'}).then((res) => {
        console.log(res) // 点击了确定按钮
      }).catch((err) => {
        console.log(err) // 点击了取消按钮
      })
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

神烦大人

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值