vue3 各个工具类的封装(长期更新,建议收藏)

前言

现在 vue3 已经越来越多人使用了,为了提高开发的效率,这里封装了很多的工具类,让大家的开发过程更加的酣畅淋漓。

axiosapi 的封装

一般选择在pages同级的根目录下,创建utils文件夹,utils文件夹下创建axios.ts

  • utils/axios.ts
import axios, { AxiosResponse, AxiosRequestConfig } from 'axios';
import router from "@/router";
import { pinia, notification } from "@/utils/utils"; // 工具类
import { storage } from '@/utils/storage'; // 缓存

// 状态管理 pinia
import userStore from '@/store/user'

const useUserStore = userStore(pinia)

let baseURL: string = ''

// 这一步的目的是判断出当前是开发环境还是生成环境,方法不止一种,达到目的就行
if (process.env.NODE_ENV == "development") {
    baseURL = 'http://development.com/api/'
} else {
    baseURL = 'http://pro.com/api/'
}

console.log(process.env.NODE_ENV, 'node-env')

let config = {
    baseURL: baseURL,
    timeout: 30000  // 设置最大请求时间
}

const service = axios.create(config);

// 请求拦截
service.interceptors.request.use(
    (config: AxiosRequestConfig) => {
        // do something
        // 处理请求头等逻辑
        config.headers = config.headers || {}
        config.headers.token = storage.get('token') || ''
        return config;
    },
    (error: any) => {
        Promise.reject(error);
    }
);

// 响应拦截
service.interceptors.response.use(
    async (res: AxiosResponse) => {
        const code: number = res.data.code
        // 未登录
        if (code === 1001) {
            notification('错误提示', res.data.msg, 'error')
            // 用户信息、token、部分缓存等数据的清空
            // 跳转到登录页/注册页等逻辑
            router.push({path: '/login'})
            return Promise.reject(res.data)
        }

        return res.data
    },
    (error: any) => {
        // 可能有些接口时在这里处理未登录等清空,根据接口的性质来搬运
        return Promise.reject(error);
    }
);

export default service;

pages同级的根目录下,创建api文件夹,api文件夹下创建index.ts

  • api/index.ts
import request from '@/utils/axios';

/**
 * 作者:故蓝寻
 * 时间:2023/01/13 14:25:35
 * 功能:获取列表
 */
export const getList = (params: Object) => {
    return request({
        url: '/getList',
        method: 'get',
        params: params
    });
};

/**
 * 作者:故蓝寻
 * 时间:2022/01/13 14:25:35
 * 功能:设置数据
 */
export const setData = (params: Object = {}) => {
    return request({
        url: '/setData',
        method: 'post',
        params: params
    });
};

使用:

import { getData } from '@/api/index'; // 接口
import { loading, notification } from "@/utils/utils"; // 工具类

/**
 * 作者:故蓝寻
 * 时间:2023/03/26 12:20:02
 * 功能:获取详情
 */
const onGetData = () => {
  loading() // load加载
  getData({
    id: 1
  }).then(res => {
    loading().close() // 关闭load加载
    if (res.code === 1) {
      notification('成功提示', res.msg, 'success')
      // 逻辑处理
    }
  }).catch(e => {
    notification('错误提示', res.msg, 'error')
    loading().close()
    // 错误的逻辑处理
  })
}

storage 的封装

utils文件夹下创建storage.ts

  • utils/storage.ts
/**
 * 封装操作localstorage本地存储的方法
 */
export const storage = {
    //存储
    set(key: string, value: any) {
        localStorage.setItem(key, JSON.stringify(value))
    },
    //取出数据
    get<T>(key: string) {
        const value = localStorage.getItem(key)
        if (value && value != "undefined" && value != "null") {
            return <T>JSON.parse(value)
        }
    },
    // 删除数据
    remove(key: string) {
        localStorage.removeItem(key)
    }
};

/**
 * 封装操作sessionStorage本地存储的方法
 */
export const sessionStorage = {
    //存储
    set(key: string, value: any) {
        window.sessionStorage.setItem(key, JSON.stringify(value))
    },
    //取出数据
    get<T>(key: string) {
        const value = window.sessionStorage.getItem(key)
        if (value && value != "undefined" && value != "null") {
            return JSON.parse(value)
        }
        return null
    },
    // 删除数据
    remove(key: string) {
        window.sessionStorage.removeItem(key)
    }
}

使用:

import { sessionStorage, storage } from '@/utils/storage' // 引入

storage.set('token', 'token')
storage.get('token')
storage.remove('token', 'token')

utils 的封装(长期完善)

utils文件夹下创建utils.ts

  • utils/utils.ts
import router from "@/router";
import { ElLoading, ElNotification } from 'element-plus';
import { createPinia } from "pinia";

/**
 * 这里设置pinia的原因很简单,pinia模块化的时候,在main.ts里需要注册createPinia()
 * 但是main.ts在注册的话,axios.ts更新pinia就不能在其它地方获取,相当于创建了两个pinia
 * 如果没有使用pinia模块化可忽略这里
 */
export const pinia = createPinia()

/**
 * 功能:获取路由参数
 * 使用:解构 const { id } = routerParam,或 let routerParam = routerParam()
 */
export function routerParam(){
    return router.currentRoute.value.query
}

const loadOptions = {
    lock: false,
    text: '加载中...',
    background: 'rgba(255, 255, 255, 0.5)',
}
/**
 * 功能:loading
 * 使用:loading() 触发加载,loading.close() 关闭加载
 */
export function loading(options = loadOptions){
    return ElLoading.service(options)
}

/**
 * 功能:通知
 */
export function notification(title: string = '提示', message: string, type: 'success' | 'error' | 'warning' | 'info'){
    ElNotification({
        title,
        message,
        type,
    })
}

/**
 * 功能:路由解析并且拼接
 * 使用:parseUrl('home', {id:1,type: 'add'})
 * 返回:'/pages/home?id=1&type=add'
 */
export function parseUrl(url: '', params: any) {
    let arr = [];
    let string = '';
    for (let i in params) {
        arr.push(i + "=" + params[i]);
    }

    string = "/pages/" + url;
    if (arr.length > 0) {
        string += "?" + arr.join("&");
    }

    return string;
}

/**
 * 功能:判断数据类型
 */
export function isDataType(data: any, type: any) {
    return Object.prototype.toString.call(data) === '[object ' + type + ']';
}

/**
 * 功能:判断数组里是否有某个key
 */
export function in_array(search: any, array: []) {
    let flag = false;
    for (let i in array) {
        if (array[i] == search) {
            flag = true;
            break;
        }
    }

    return flag;
}
  • 2
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

故蓝寻

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

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

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

打赏作者

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

抵扣说明:

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

余额充值