场景:在项目开发过程中大概率会出现复用性方法,故为了节省代码量对公共方法进行抽象提取,将其封装为公共方法,以便于在不同组件中快速使用。
举例分页器方法提取:
src下新建hooks文件夹,新增ts文件:
文件内提取方法:
import { TABLE_PAGE } from '@/core/constants';
import { reactive, ref } from 'vue';type sortParam = {field?: string | null;desc?: number | null;
};export default function useSubTable(param: any) {const subPage = reactive({...TABLE_PAGE});const subQuery = reactive({} as sortParam);const subSearchParam: any = ref({});const subTableLoading = ref<boolean>(false);const subTableData = ref<any[]>([]);const getSubList = () => {if (param?.getSubList) {param.getSubList();}};const subChangePageSize = (size: number) => {subPage.pageSize = size;getSubList();};const subChangeCurrentPage = (pageNum: number) => {subPage.page = pageNum;getSubList();};const subChangeSort = (field: string, order: string) => {subQuery.field = field;subQuery.desc = order === 'asc' ? 0 : order === 'desc' ? 1 : null;getSubList();};const resetSubPage = () => {subPage.page = TABLE_PAGE.page;subPage.pageSize = TABLE_PAGE.pageSize;subPage.total = TABLE_PAGE.total;subQuery.field = null;subQuery.desc = null;subSearchParam.value = {};subTableData.value = [];};const subCommomSearch = () => {subChangeCurrentPage(1);};return {subPage,subQuery,subSearchParam,subChangePageSize,subChangeCurrentPage,subChangeSort,subCommomSearch,resetSubPage,subTableLoading,subTableData};
}
组件内使用:
import useSubTabel from "@/hooks/useSubTable";
//结构需要使用的方法
const {subPage,subSearchParam,subChangePageSize,subChangeCurrentPage,resetSubPage,subCommomSearch,subTableLoading,subTableData
} = useSubTabel({getSubList
});