公共Hooks封装之请求参数useQueryParams

写在前面

对于经常需要开发企业管理后台的前端开发来说,必不可少的需要使用表格对于数据进行操作,在对于现有项目进行代码优化时,封装一些公共的Hooks. 本篇文章为useQueryParams.js

基于个人项目环境进行封装的Hooks,仅以本文介绍封装Hooks思想心得,故相关代码可能不适用他人

项目环境

Vue3.x + Ant Design Vue3.x + Vite3.x

此篇内容讲解的是关于公共Hooks封装之表格数据useTableData中暴露出来与queryParams的一些方法,而进行封装的Hooks,其目的在于减少冗余重复代码的书写。

封装分解:参数定义

const defaultParams = clone(params);  // 作为Hooks被使用后,克隆页面内声明常见的请求参数,可理解为静态参数
const queryParams = ref({ ...defaultParams });

封装分解:合并参数

const mergeParams = params => {
  queryParams.value = Object.assign({}, queryParams.value, params);
};

合并参数的使用场景则是页面内请求数据的一些动态参数,例如子组件(弹窗Modal、抽屉Drawer)等被打开同时需要请求数据(明细Table、编辑信息Info),往往需要对应唯一Key来调用接口

合并参数--范例

代码范例仅解释合并参数mergeParams用法,且只有关键用法

父组件代码:

<a-table>
  <template #bodyCell="{ column, record }">
    <template v-if="column.key === 'action'">
      <span class="cl-link cursor-pointer" @click="showDetail(record.ID)">明细</span>
    </template>
  </template>
</a-table>

<detail :only-key="curKey" v-model:visible="drawerVisible" />

<script setup>
  const showDetail = Id => {
    drawerVisible.value = true;
    curKey.value = Id
  }
</script>

子组件代码:

<script setup>
watch(
  () => props.visible,
  newVal => {
    if (newVal) {
      mergeParams({
        onlyKey: props.onlyKey,
      });
      queryParams.value.pageIndex = 1;
      getTableData();
    }
  },
);
</script>

useQueryParams.js完整代码

import { ref } from 'vue';
import { clone } from 'lodash-es';

export function useQueryParams(params) {
  const defaultParams = clone(params);
  const queryParams = ref({ ...defaultParams });

  const resetParams = () => {
    queryParams.value = { ...defaultParams };
  };

  const mergeParams = params => {
    queryParams.value = Object.assign({}, queryParams.value, params);
  };

  return {
    queryParams,
    resetParams,
    mergeParams,
  };
}
最近更新时间: