Vue开发公共模块封装(msg)

本文介绍基于vux简单封装msg模块。
*主要利用vue.use()方法来安装插件,安装 Vue.js 插件。如果插件是一个对象,必须提供 install 方法。如果插件是一个函数,它会被作为 install 方法。install 方法将被作为 Vue 的参数调用。
当 install 方法被同一个插件多次调用,插件将只会被安装一次。*

import Vue from 'vue'
import { ToastPlugin, AlertPlugin, ConfirmPlugin, LoadingPlugin } from 'vux'
/*import { Promise } from 'es6-promise';*/

Vue.use(ToastPlugin)
Vue.use(AlertPlugin)
Vue.use(ConfirmPlugin)
Vue.use(LoadingPlugin)

const Message = {};
Message.install = () => {
    const msg = {
        $toast: config => {
            let def = {
                type:'text',
                text:''
            }
            if(typeof  config  === 'string' || typeof  config  === 'number'){
                Vue.$vux.toast.show({type:'text',text:config})
            }else{
                Vue.$vux.toast.show(Object.assign(def,config))
            }

        },
        $alert: config => {
            let def = {
                title:'提示',
                content:'系统异常,请重新登录后再试!',
                buttonText:'确定'
            }
            if(typeof  config  === 'string' || typeof  config  === 'number'){
                Vue.$vux.alert.show(Object.assign(def,{content:config}));
            }else{
                Vue.$vux.alert.show(Object.assign(def,config));
            }
        },
        $confirm: config => {
            let isConfirm = false;
            let def = {
                title:'提示',
                content:'系统异常,请重新登录后再试!',
                confirmText:'确定',
                cancelText:'取消',
                onConfirm:() =>{
                    isConfirm = true;
                }
            }
            if(typeof  config  === 'string' || typeof  config  === 'number'){
                Vue.$vux.confirm.show(Object.assign(def,{content:config}));
            }else{
                Vue.$vux.confirm.show(Object.assign(def,config));
            }
            /*return new Promise((resolve,reject) => {
                if(isConfirm){
                    resolve();
                }
            })*/
        },
        $showLoading: config => {
            let def = {
                text: '加载中...'
            }
            if(typeof  config  === 'string' || typeof  config  === 'number'){
                Vue.$vux.loading.show(Object.assign(def,{text:config}));
            }else{
                Vue.$vux.loading.show(Object.assign(def,config));
            }
        }

    }
    Object.entries(msg).forEach(([method,fn]) => {
        Vue.prototype[method] = fn;
    })
}
Vue.use(Message)

简单将消息弹框封装进vue的原型当中,这样我们在组件中就可以很方便地使用。比如在某个组件中:

this.$alert({
          content: 'xxxx',
          onHide() {
            this.$router.replace('/index/ywbl');
          }
        })

这样我们便不用每次都引入相应的ui模块了。

你可能感兴趣的:(vue)