Vue3 writes list request and paging status control in one line of code? Tips to increase your fishing time and get off work on time

Project scenario

Anyone who has written small programs or h5 and other mobile terminals knows that there will be paging when requesting the background list interface.

Benefits of pagination

  • 1. Improve the interface response speed (as we all know, there is definitely a difference in the response time between checking 10 pieces of data and checking 10,000 pieces of data)
  • 2. Improve front-end rendering performance and detect all data at once. The front-end will freeze if it does not make a virtual list.
  • 3. Save server pressure

Questions raised

Xiaosheng Bibi: The pressure on your server is reduced. The amount of code has increased. Each page needs to define the status of the current list (whether there is a next page), which page the current list is, and the list needs to be accumulated. How many requests per page! I'm just a bad coder. I just want to get off work early! ! Especially when one page requests several lists, it is very annoying to write these repeated codes, okay?

So how to reuse these repeated parameters with only one line of code? ? We can solve it using hooks

Previous practice

define type

Insert image description here

Write the request method and set the list data and status

Insert image description here

Current practice

Define type + request method

Insert image description here
It's that simple, just use it and it's done

The origin of hooks

Hooks are a new feature in react 16.8.0. I happened to be writing react at that time. Anyone who has written react knows that at that time, class components were the mainstream, and hooks were

What the hell? ? Is it easy to use? Let’s see what problems hooks solve.

  • 1. It is difficult to reuse state logic between components

  • 2. Complex components become difficult to understand

  • 3. Incomprehensible classes (the class components mentioned above)

I used it for a while and felt that this thing is really easy to use. It is much more convenient to write than class components. You can just introduce it and use it.

Vue3: React, you guys have a good idea of ​​hooks, I’ll use them to you

At this time, we also have various hooks in our vue3

Custom hooks

Hooks are generally named useXXXXX. We recommend a vue official hooks library, vueUses, which contains various miscellaneous hooks. Unfortunately, this library is an English document, but it is not a big problem. It does not affect its ease of use at all
vueUses official website address

Interface function examples and response examples

export interface IListResponse<T> {
    
    
    code: number
    rows: T,
    msg: string,
    [key: string]: any
}
export type TApiListRequest<T> = Promise<IListResponse<T>>
/**
 * 客户列表
 * @param params
 * @returns
 */
export const reqCustomerlistPage = <T>(params?: T): TApiListRequest<ICustomerListItem[]> => {
    
    
    return new Promise(async (resolve) => {
    
    
        const url = `/core/customer/listPage`;
        let result = await $http.post(url, params);
        resolve(result);
    });
};

List request code for custom hooks


interface IUseRequestListConfig<T> {
    
    
    /** 当前页自定义请求字段,默认是pageNum */
    pageNumFields?: string
    /** 每页数量自定义请求字段,默认是pageSize */
    pageSizeFields?: string
    /** 返回数据中列表的字段,默认是rows */
    dataFields?: string
    /**封装好的接口api */
    apiFunction: (params?: any) => TApiListRequest<T[]>
}
// 加载状态
enum TLoadStatus {
    
    
  LOAD_MORE = 'loadmore', //# 加载更多
  LOADING = 'loading', //#加载中
  NOMORE = 'nomore', //#没有更多
}
/**
 * 列表请求hooks
 * @param originConfig 配置
 * @returns 
 */
export const useRequestList = <T>(originConfig: IUseRequestListConfig<T>) => {
    
    
    // 默认配置
    const defaultConfig = {
    
     pageNumFields: "pageNum", pageSizeFields: "pageSize", dataFields: "rows" }
    // 合并后配置
    const config: IUseRequestListConfig<T> = {
    
     ...defaultConfig, ...originConfig }
    interface IState {
    
    
        params: {
    
    
            [x: string]: number;
        };
    }
    const state = reactive<IState>({
    
    
        params: {
    
    
            [config.pageNumFields!]: 1,
            [config.pageSizeFields!]: 10,
        },
    })
    const dataSource = ref<T[]>([])
    const status = ref<TLoadStatus>(TLoadStatus.LOAD_MORE)
    /**
     * 加载数据
     * @param otherParams 
     * @returns 
     */
    const loadData = async <T extends Record<string, unknown>>(otherParams?: T) => {
    
    
        if (status.value === TLoadStatus.NOMORE) return;
        status.value = TLoadStatus.LOADING;
        let result = await config.apiFunction({
    
     ...state.params, ...otherParams });
        if (state.params.pageNum === 1) dataSource.value = [];
        state.params.pageNum += 1;
        dataSource.value = [...dataSource.value, ...result[config.dataFields!]];
        status.value = dataSource.value.length < result.total ? TLoadStatus.LOAD_MORE : TLoadStatus.NOMORE;
    }
    /**
     * 刷新列表
     * beforeRfresh用于在刷新之前清空某些查询字段
     */
    const handleRefresh = async <T extends Record<string, unknown>>(otherParams?: T, beforeRfresh?: () => void) => {
    
    
        beforeRfresh?.()
        status.value = TLoadStatus.LOAD_MORE;
        state.params = {
    
    
            ...state.params,
            [config.pageNumFields!]: 1,
        };
        await loadData(otherParams);
    };
    return {
    
    
        loadData,
        dataSource,
        status,
        handleRefresh
    }
}

Instructions

const {
    
     handleRefresh, loadData, status, dataSource } = useRequestList({
    
     apiFunction: reqCustomerlistPage });

That's right, requesting a list can be done with one line of code (I can finally fish happily).
During use, just throw the hooks method in the life cycle and hook function that need to be requested. In this hook, the returned data and The status of the current list is responsive. To load more components at the bottom of the list, you need to give the current status by modifying the TLoadStatus enumeration. The loading status of some component libraries may be 0, 1, 2, and some may be like me. of.

Guess you like

Origin blog.csdn.net/wz9608/article/details/128189567