网络请求
介绍
网络请求,没有使用Axios,采用了VueUse的一个函数useFetch,与Axios 在使用上有明显的区别,使用中需要注意
api封装
基本未进行API请求封装,将API的分成四大类,
更新修改==> put==> usePut 
数据新增==>post==>usePost 
数据删除==>delete==>useDelete 
数据获取==>get   ==>useGet 
对api 主要进行了 enum ,如下
export enum ApiSysDictType {
  // dict type
  getById = '/system/dict/type/get_by_id',
  getList = '/system/dict/type/list',
  edit = '/system/dict/type/edit',
  add = '/system/dict/type/add',
  delete = '/system/dict/type/delete',
}
/**
  @description: 字典数据Api
   */
export enum ApiSysDictData {
  getByType = '/system/dict/data/get_by_type',
  getById = '/system/dict/data/get_by_id',
  getList = '/system/dict/data/list',
  edit = '/system/dict/data/edit',
  add = '/system/dict/data/add',
  delete = '/system/dict/data/delete',
}
 
然后统一归在一起,方便使用
export type APIS =
  | ApiSysDictType
  | ApiSysDictData
 
数据返回
后端定义了统一的数据返回格式
export interface responseData {
  code: number
  data: any | null
  msg: string
}
 
并前端进行了拦截,只返回data 部分给页面使用,如果发生错误,将全局通知消息msg部分,并将data设置为ErrorFlag,可以在读取数据前,先判断,见如下
const { data, execute } = usePut(ApiSysUser.changeDept, {
    user_id: userStore.user.uid,
    dept_id: v,
  })
  await execute()
  if (data.value === ErrorFlag) return
  ElMessage.success(t('nav.changeDeptTip'))
 
如果发生错误,将不提示ElMessage.success(t('nav.changeDeptTip'))该消息,只提示后端返回的错误信息
列表数据
定义的数据格式如下
export interface post extends operateInfo {
  post_id?: string
  post_code?: string
  post_name?: string
  post_sort?: number
  status?: string
  remark?: string
}
export interface postList extends pageData {
  list: post[]
}
export interface postQueryParam extends pageQueryParam {
  post_code?: string
  post_name?: string
  status?: string
}
 
useListData
第一种使用useListData hook 函数
函数定义如下:
export interface listType<V extends operateInfo> extends pageData {
  list: V[]
}
/**
 * 列表数据相关数据;
 * Q为查询参数泛型;
 * V返回结果泛型;
 * @param queryParam 请求参数
 */
export const useListData = <Q extends pageQueryParam, V extends operateInfo>(
  api: APIS,
  queryParam: Ref<Q>,
  time?: Ref<string[]>
) => {
  const list = ref<V[]>([]) as Ref<V[]>
  const total = ref(0)
  /**
   * 获取数据列表
   */
  const getListFn = async () => {
    if (time) {
      queryParam.value = addTimeQueryParam(queryParam.value, time?.value)
    }
    const { data, execute } = useGet<listType<V>>(api, queryParam)
    await execute()
    list.value = data.value?.list!
    total.value = data.value?.total!
  }
  getListFn()
  return {
    getListFn,
    list,
    total,
  }
}
 
使用方式如下,需要传入正确的泛型参数
const {
  list: postListData,
  getListFn: getList,
  total,
} = useListData<postQueryParam, post>(ApiSysPost.getList, queryParams)
 
这种方式使用,数据异步请求,返回的数据是响应式数据,如果使用console.log() 打印数据,将全部是undefined数据,需要注意,打印时,一般数据都还没有返回
useGet
第二中使用方式
const postData= ref<post[]>([])
const getData = async () => {
  const { data, execute } = useGet<postList>(
    ApiSysPost.getList,
    queryParams
  )
  await execute()
  postData.value = data.value?.list!
}
 
需要在函数体中执行,然后赋值给定义好的数据