vue封装axios、element-ui消息提示、element-plus消息提示

1、axios封装

//引入axios
import axios from 'axios'
//引入登录拦截
import store, {
     TOKEN_HEADER} from "../store";
//引入路由
import router from "../router";
//引入定义链接
import {
     reUrl, path} from './urls'
//引入qs
import qs from 'qs'

import {
     
    // eslint-disable-next-line no-unused-vars
    MessageBox,
    Loading
} from 'element-ui'
import message from "./message";

//axios定义
axios.defaults.baseURL = reUrl;
//axios.defaults.headers['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8'
//axios.defaults.transformRequest = [object => qs.stringify(object)]

axios.defaults.headers['Content-Type'] = 'application/json'
axios.defaults.timeout = 3000;
axios.defaults.withCredentials = true;
// axios request 拦截器
axios.interceptors.request.use(
    config => {
     
        //判断token是否存在
        if (store.state.token !== null) {
     
            //将token设置成请求头
            config.headers[TOKEN_HEADER] = store.state.token;
        }
        return config;
    },
    err => {
     
        return Promise.reject(err);
    }
);
// http response 拦截器
axios.interceptors.response.use(
    res => {
     
        if (res.data.code === 102) {
     
            store.commit('delToken');
            store.commit('delUserInfo');
            router.push(path('/login.html')).then();
        } else if (res.data.code === 500 || res.data.code === 403) {
     
            message.alert({
     title: '错误', msg: res.data.msg});
        } else {
     
            return res;
        }
    },
    error => {
     
        return Promise.reject(error);
    }
);

const request = (object) => {
     
    let loading = null;
    if (object.loading) {
     
        loading = Loading.service({
     
            lock: true,
            text: object.loading,
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.6)'
        });
    }
    if (!object.timeout) {
     
        object.timeout = 0;
    }
    axios({
     
        method: object.method,
        url: object.url,
        data: object.dataType
    }).then((res) => {
     
        setTimeout(() => {
     
            if (object.loading) {
     
                loading.close();
            }
            if (!res) {
     
                return;
            }
            const data = res.data;
            if (data.code !== 403 && data.code !== 500) {
     
                if (isFunction(object.success)) {
     
                    object.success(data);
                }
            }
        }, object.timeout);
    }).catch((error) => {
     
        console.log(error);
        setTimeout(() => {
     
            if (object.loading) {
     
                loading.close();
            }
            if (isFunction(object.error)) {
     
                object.error(error);
            } else {
     
                message.alert({
     
                    title: '错误', msg: '请求出错'
                });
            }
        }, object.timeout);
    });
}

const isFunction = (func) => {
     
    return func && typeof func == 'function'
}

const executeReq = (object) => {
     
    if (object.confirm) {
     
        message.confirm({
     
            msg: object.confirm,
            func: () => request(object)
        });
    } else {
     
        request(object);
    }
}

export default {
     
    /**
     *
     * @param url 链接
     * @param data 数据
     * @param loading 是否开启 loading
     * @param timeout loading的关闭时间 不提供则为 0
     * @param confirm 是否需要 confirm 提示
     * @param success 成功返回
     * @param error 失败返回
     */

    get({
     url, data, loading, timeout, confirm, success, error}) {
     
        const method = 'GET';
        if (data) {
     
            data = qs.stringify(JSON.parse(JSON.stringify(data)));
            url = url + "?" + data;
        }
        executeReq({
     method, url, data, loading, timeout, confirm, success, error});
    },
    post({
     url, data, loading, timeout, confirm, success, error}) {
     
        const method = 'POST';
        executeReq({
     method, url, data, loading, timeout, confirm, success, error});
    },
    put({
     url, data, loading, timeout, confirm, success, error}) {
     
        const method = 'PUT';
        executeReq({
     method, url, data, loading, timeout, confirm, success, error});
    },
    delete({
     url, data, loading, timeout, confirm, success, error}) {
     
        const method = 'DELETE';
        executeReq({
     method, url, data, loading, timeout, confirm, success, error});
    }
}

1.1、上述需要用到的 urls
// 前端url前缀
export const feUrl = '/sake/qingjiu';
// 后端url前缀
export const reUrl = 'http://192.168.101.68:9949/sake';
// 图片url前缀
export const imgUrl = reUrl + '/img/';

// 返回链接路径
export const path = (path) => {
     
    return feUrl.concat(path);
}

2、element-ui 的 message(消息提示)封装

import {
     MessageBox, Message} from 'element-ui'

const message = (msg, type) => {
     
    Message({
     
        showClose: true,
        message: msg,
        type: type
    });
}
//成功
const success = (msg) => {
     
    message(msg, 'success');
}
//消息
const info = (msg) => {
     
    message(msg, 'info');
}
//错误
const error = (msg) => {
     
    message(msg, 'error');
}
//警告
const warning = (msg) => {
     
    message(msg, 'warning');
}

//ElMessageBox
const alert = ({
     title, msg, okBtnText, func}) => {
     
    if (!title) {
     
        title = '提示';
    }
    if (!msg) {
     
        msg = '错误';
    }
    if (!okBtnText) {
     
        okBtnText = '确定';
    }
    MessageBox.alert(msg, title, {
     
        confirmButtonText: okBtnText,
    }).then(func ? func : () => {
     })
}

const confirm = ({
     title, msg, func, cFunc}) => {
     
    MessageBox.confirm(msg, title ? title:'提示', {
     
        confirmButtonText: '确定',
        cancelButtonText: '取消',
    }).then(func ? func : () => {
     }).catch(cFunc ? cFunc : () => {
     });
}

export default {
     
    success,
    info,
    error,
    warning,
    alert,
    confirm,
}

2、element-plus 的 message(消息提示)封装

import {
     ElMessageBox, ElMessage} from 'element-plus'

const message = (msg, type) => {
     
    ElMessage({
     
        showClose: true,
        message: msg,
        type: type
    });
}
//成功
const success = (msg) => {
     
    message(msg, 'success');
}
//消息
const info = (msg) => {
     
    message(msg, 'info');
}
//错误
const error = (msg) => {
     
    message(msg, 'error');
}
//警告
const warning = (msg) => {
     
    message(msg, 'warning');
}

//ElMessageBox
const alert = ({
     title, msg, okBtnText, func}) => {
     
    if (!title) {
     
        title = '提示';
    }
    if (!msg) {
     
        msg = '错误';
    }
    if (!okBtnText) {
     
        okBtnText = '确定';
    }
    ElMessageBox.alert(msg, title, {
     
        confirmButtonText: okBtnText,
    }).then(func ? func : () => {
     });
}

const confirm = ({
     title, msg, func, cFunc}) => {
     
    ElMessageBox.confirm(msg, title ? title:'提示', {
     
        confirmButtonText: '确定',
        cancelButtonText: '取消',
    }).then(func ? func : () => {
     }).catch(cFunc ? cFunc : () => {
     });
}

export default {
     
    success,
    info,
    error,
    warning,
    alert,
    confirm,
}

你可能感兴趣的:(axios,element-ui,element-plus,vue)