1. 当前位置:网站首页 > Vue

vue3的axios钩子方法


钩子方法

建立request.ts 方法存入src/utils路径下

import axios from 'axios';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Session } from '/@/utils/storage';

// 配置新建一个 axios 实例
const service = axios.create({
    baseURL: import.meta.env.VITE_API_URL as any,
    timeout: 50000,
    headers: { 'Content-Type': 'application/json' },
});

// 添加请求拦截器
service.interceptors.request.use(
    (config) => {
        // 在发送请求之前做些什么 token追加到头
        if (Session.get('token')) {
            config.headers.common['Authorization'] = 'JWT '+ `${Session.get('token')}`;
        }
        return config;
    },
    (error) => {
        // 对请求错误做些什么
        return Promise.reject(error);
    }
);

// 添加响应拦截器
service.interceptors.response.use(
    (response) => {
        const res = response.data;
        if (res.status && res.status !== 0) {
            // `token` 过期或者账号已在别处登录
            if (res.status === 401 || res.status === 4001) {
                Session.clear(); // 清除浏览器全部临时缓存
                window.location.href = '/'; // 去登录页
                ElMessageBox.alert('你已被登出,请重新登录', '提示', {})
                    .then(() => {})
                    .catch(() => {});
            }
            return response.data;
        }

    },
    (error) => {
        if(error.response.data.hasOwnProperty('non_field_errors')){
            ElMessage.error(error.response.data.non_field_errors[0]);
        }else{
            // 对响应错误做点什么
            if (error.message.indexOf('timeout') != -1) {
                ElMessage.error('网络超时');
            } else if (error.message == 'Network Error') {
                ElMessage.error('网络连接错误');
            } else {
                if (error.response.data) ElMessage.error(error.response.statusText);
                else ElMessage.error('接口路径找不到');
            }
        }

    }   
);
// 导出 axios 实例
export default service;

src路径下建立api目录,新建api.ts文件(这里我以登录为例)

import request from '/@/utils/request';

/**
 * 用户登录
 * @param params 要传的参数值
 * @returns 返回接口数据
 */
export function signIn(params: object) {
    return request({
        url: '/api/signIn',
        method: 'post',
        data: params,
    });
}

/**
 * 用户退出登录
 * @param params 要传的参数值
 * @returns 返回接口数据
 */
export function signOut(params: object) {
    return request({
        url: '/api/signOut',
        method: 'post',
        data: params,
    });
}

在view文件中引用

import { ref, toRefs, reactive, defineComponent, computed, getCurrentInstance, onMounted } from 'vue';
import { formatAxis } from '/@/utils/formatTime';
import {signIn, signOut} from '/@/api/api';
export default defineComponent({
    name: 'loginAccount',
    setup() {
        const state = reactive({
            isShowPassword: false,
            ruleForm: {
                username: 'admin',
                password: '123456',
            },
            loading: {
                signIn: false,
            },
        });
        // 时间获取
        const currentTime = computed(() => {
            return formatAxis(new Date());
        });
        // 登录
        const onSignIn = async () => {
            state.loading.signIn = true;

            signIn(state.ruleForm).then((res) => {
                if (typeof(res) == "undefined"){
                    state.loading.signIn = false;
                }else{
                    // 用户信息数据
                    const userInfos = {
                        userName: state.ruleForm.username,
                        userId: res.user_id,
                        time: new Date().getTime(),
                    };  
                    .....
                    state.loading.signIn = false;
                }
            }); 
        };
        return {
            currentTime,
            onSignIn,
            ...toRefs(state),
        };
    },
});

本文最后更新于2022-7-12,已超过 3个月没有更新,如果文章内容或图片资源失效,请留言反馈,我们会及时处理,谢谢!
版权说明

本文地址:http://www.liuyangdeboke.cn/?post=27
未标注转载均为本站远程,转载请注明文章出处:

发表评论

联系我们

在线咨询:点击这里给我发消息

微信号:17721538135

工作日:9:00-23:00,节假日休息

扫码关注