接口请求参数类型
修改 src/api/request.ts
核心代码:
// GET 请求
// @param url 请求地址
// @param params 查询参数
// @return 返回Promise对象,内部类型是泛型
function get<T>(url: string, params: object): Promise<T> {return req.get(url, {params})
}// POST 请求
// @param url 请求地址
// @param data 请求参数
// @return 返回Promise对象,内部类型是泛型
function post<T>(url: string, data: object): Promise<T> {return req.post(url, data)
}
完整代码:
import axios from "axios";
import {message} from "antd";
import {hideLoading, showLoading} from "@/components/loading/Index.tsx";// 创建实例
const req = axios.create({baseURL: '/api',timeout: 3000,timeoutErrorMessage: "请求超时,请稍后再试",withCredentials: true, // 跨域headers: {'Content-Type': 'application/json',}
})// 请求拦截器
req.interceptors.request.use(// 拦截配置并更新配置config => {// 请求开始之前要展示加载状态showLoading()// 获取登录tokenconst token = localStorage.getItem("token")// 使用 JWT Tokenif (token) {config.headers.Authorization = "Bearer " + token}// 将修改后的配置返回return {...config}},// 拦截错误并注入错误信息error => {// 关闭加载状态hideLoading()// 返回错误信息return Promise.reject(error);}
)// 响应拦截器
req.interceptors.response.use(// 拦截正常响应response => {// 关闭加载状态hideLoading()// 获取服务端响应的数据const data = response.data// 响应成功if (data.code === 10000 && data.status === true) {return data.data}// 响应失败:权限错误if (data.code === 10401 || data.status === 10403) {message.error(data.msg)localStorage.removeItem("token")location.href = "/login"return}// 其他错误message.error(data.msg)return Promise.reject(data)},// 拦截错误响应error => {// 关闭加载状态hideLoading()// 返回错误信息message.error(error.message)return Promise.reject(error.message);}
)// GET 请求
// @param url 请求地址
// @param params 查询参数
// @return 返回Promise对象,内部类型是泛型
function get<T>(url: string, params: object): Promise<T> {return req.get(url, {params})
}// POST 请求
// @param url 请求地址
// @param data 请求参数
// @return 返回Promise对象,内部类型是泛型
function post<T>(url: string, data: object): Promise<T> {return req.post(url, data)
}// 导出
export {req,get,post,
}
封装 storage
src/util/storage.ts
// 全局的key,防止本地有多个项目同key冲突
const project_key = "zdpreact_tsadmin";// 设置值
// @param key 要存储的key
// @param value 要存储的value
function set(key: string, value: any) {key = `${project_key}__${key}`localStorage.setItem(key, JSON.stringify(value))
}// 读取值
// @param key 存储的key
function get(key: string) {// 读取key = `${project_key}__${key}`const value = localStorage.getItem(key)if (!value) return ''// 优先解析JSON,否则返回原值try {return JSON.parse(value)} catch (err) {return value}
}// 删除值
// @param key 存储的key
function remove(key: string) {key = `${project_key}__${key}`localStorage.removeItem(key)
}// 清空值,不建议使用
function clear() {localStorage.clear()
}// 存储对象
const storage = {set,get,remove,clear,
}
export default storage
测试
修改 src/page/Index.tsx
import {Button} from "antd";
import {useState} from "react";
import storage from "@/util/storage.ts";export default function Index() {const [value, setValue] = useState("")const handleSet = () => {storage.set("value", "hello")}const handleGet = () => {setValue(storage.get("value"))}const handleRemove = () => {storage.remove("value")setValue(storage.get("value"))}const handleClear = () => {storage.clear()setValue(storage.get("value"))}return (<div><h1>Index</h1><h2>当前值:{value}</h2><section><Button onClick={handleSet}>写入</Button><Button onClick={handleGet}>读取</Button><Button onClick={handleRemove}>删除</Button><Button onClick={handleClear}>清除</Button></section></div>)
}
此时,访问 http://localhost:5173/ 进行测试。
封装 number
src/util/number.ts
// 将数字转换为人民币格式
function rmb(num: number | string) {const value = parseFloat(num.toString())return value.toLocaleString("zh-CN", {style: "currency", currency: "CNY"})
}// 导出
export default {rmb,
}
测试
修改 src/page/Index.tsx
核心代码:
const handleGet = () => {const v = storage.get("value")setValue(number.rmb(v))
}
完整代码:
import {Button} from "antd";
import {useState} from "react";
import storage from "@/util/storage.ts";
import number from "@/util/number.ts";export default function Index() {const [value, setValue] = useState("")const handleSet = () => {storage.set("value", "123456789")}const handleGet = () => {const v = storage.get("value")setValue(number.rmb(v))}const handleRemove = () => {storage.remove("value")setValue(storage.get("value"))}const handleClear = () => {storage.clear()setValue(storage.get("value"))}return (<div><h1>Index</h1><h2>当前值:{value}</h2><section><Button onClick={handleSet}>写入</Button><Button onClick={handleGet}>读取</Button><Button onClick={handleRemove}>删除</Button><Button onClick={handleClear}>清除</Button></section></div>)
}
此时,访问 http://localhost:5173/ 进行测试。
封装 date
src/util/date.ts
// 日期格式化
function format(date?: Date, format?: string): string {// 获取日期时间对象let now = new Date()if (date) now = date// 日期switch (format) {case "date":return now.toLocaleDateString().replace("/", "-").replace("/", "-")case "time":return now.toLocaleTimeString()case "datetime":return now.toLocaleString().replace("/", "-").replace("/", "-")default:return now.toLocaleDateString()}
}// 导出
export default {format,
}
测试
修改 src/page/Index.tsx
核心代码:
const handleSet = () => {storage.set("value", date.format(new Date(), "datetime"))
}
const handleGet = () => {setValue(storage.get("value"))
}
完整代码:
import {Button} from "antd";
import {useState} from "react";
import storage from "@/util/storage.ts";
import date from "@/util/date.ts";export default function Index() {const [value, setValue] = useState("")const handleSet = () => {storage.set("value", date.format(new Date(), "datetime"))}const handleGet = () => {setValue(storage.get("value"))}const handleRemove = () => {storage.remove("value")setValue(storage.get("value"))}const handleClear = () => {storage.clear()setValue(storage.get("value"))}return (<div><h1>Index</h1><h2>当前值:{value}</h2><section><Button onClick={handleSet}>写入</Button><Button onClick={handleGet}>读取</Button><Button onClick={handleRemove}>删除</Button><Button onClick={handleClear}>清除</Button></section></div>)
}
此时,访问 http://localhost:5173/ 进行测试。