Foreword
For front-end developers who frequently build enterprise management backends, using tables to handle data is essential. When optimizing the code of existing projects, it’s a good practice to encapsulate some reusable hooks. This article is for ‘useQueryParams.js’.
Hooks encapsulated based on a personal project environment; this article only shares insights and best practices for hook encapsulation, so the associated code may not be suitable for 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 by 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>
Child component code:
<script setup>
watch(
() => props.visible,
newVal => {
if (newVal) {
mergeParams({
onlyKey: props.onlyKey,
});
queryParams.value.pageIndex = 1;
getTableData();
}
},
);
</script>
Complete code for useQueryParams.js
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,
};
}