HOOKS

useQueryParams of request parameters encapsulated by public Hooks

Request Parameter Encapsulation with Public Hooks: useQueryParams

Foreword

For front-end developers who frequently build enterprise management backends, working with tables to manipulate data is essential. When refactoring existing projects, it’s a good practice to encapsulate some reusable custom hooks. This article is ‘useQueryParams.js’

Hooks encapsulated based on a personal project environment; this article only shares insights and best practices for hook encapsulation, so the accompanying code may not be directly applicable to others.

Project Environment

Vue 3.x + Ant Design Vue 3.x + Vite 3.x

This article explains some methods exposed and queryParams in table data useTableData encapsulated by public Hooks, while encapsulated Hooks aims to reduce the writing of redundant and repetitive code.

Encapsulation Decomposition: Parameter Definition

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

Encapsulation decomposition: merge parameters

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

The usage scenario of merging parameters is that some dynamic parameters of the requested data in the page, such as subcomponents (pop-up window Modal, drawer Drawer), etc. are opened and the requested data (detailed Table, editing information Info) is required at the same time, and the interface is often called with a corresponding unique Key.

Merge Parameters-Example

Code examples explain only merge parameter mergeParams usage and only key usage

Parent component code:

<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>

Sub-component code:

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

useQueryParams.js complete code


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,
  };
}

Related posts

View all →