vue公共弹窗方法封装

这篇博客介绍了如何使用Vue.js封装一个Toast组件,并进行全局注册。首先展示了一个包含遮罩层、标题和主要内容的Vue模板。接着,定义了一个Toast对象,包括install方法用于注册组件,并提供了一个$toast方法供所有Vue实例使用。在main.js中引入并使用这个Toast插件,实现了弹窗功能。最后,封装了一个包含success和error方法的工具库,方便调用不同类型的提示信息。
摘要由CSDN通过智能技术生成
<template>
    <div   v-show='show'>
        <div ref="mask" class="mask" v-show="type===2"></div>
        <div class="title"><span @click="close"></span>{{title}}</div>
        <div class="main">{{message}}<span v-show="type===2" @click="close(1)">我知道了</span></div>
    </div>
</template>

export default {
    data(){
        return{
            title:'xxx',
            message:'xxxxxxxxx!', 
        }
    },
    updated(){
    
    },
    methods:{
        close(type){ 
        }
    }
}
</script>

然后新建一个js文件;

import ToastComponent from './alert.vue'// 引入先前写好的vue

const Toast = {};


// 注册Toast
Toast.install = function (Vue) {
    // 生成一个Vue的子类
    const ToastConstructor = Vue.extend(ToastComponent)
    // 生成一个该子类的实例
    const instance = new ToastConstructor();

    // 将这个实例挂载在我创建的div上
    // 并将此div加入全局挂载点内部
    instance.$mount(document.createElement('div'))
    document.body.appendChild(instance.$el);
    
    let timer = null;
    // 通过Vue的原型注册一个方法
    // 让所有实例共享这个方法 <br>    // 其中的duration是持续时间
    Vue.prototype.$toast = (msg,type = 1,title = '错误提示', duration = 2500,fun) => {
        if(instance.$data.toastBool == false)return;
        instance.$data.toastBool = false;
        clearTimeout(timer)//避免重复弹窗timer触发;造成异常;
        instance.message = msg;
        instance.type = type;
        instance.title = title;
        instance.show = true;
        instance.fun = fun;

        timer=setTimeout(() => {
            instance.$data.toastBool = true ;
            instance.show = false;
        }, duration);
    }
}

export default Toast

然后在main中调用安装

import toast from 'src'
vue.use(toast)
//此时就可以正常使用了;注意自己调整逻辑

然后封装一个弹窗方法,方便调用

export default {
    success (_this, message) {
        _this.$message({
            showClose: true,
            message,
            type: 'success'
        });
    }, 
    
};
// error:Error: Request failed with status code 401;状态码错误的;
// Error: timeout of 8000ms exceeded
//

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值