欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 文旅 > 艺术 > Vue3 中 Hooks 的应用实例

Vue3 中 Hooks 的应用实例

2025/11/26 21:34:56 来源:https://blog.csdn.net/BillKu/article/details/148130663  浏览:    关键词:Vue3 中 Hooks 的应用实例

1、定义 Hooks,装箱/封装/组合式函数

部门 Hooks,/hooks/useDepartment.ts

import { onMounted, onUnmounted, ref } from "vue";
import type { SelectOptions } from "@/interface";
import { departmentOptionsService } from "@/api/selectOptions";/*** 部门组合式函数 hooks,实现开箱即用的效果* @returns 状态(包含部门列表,部门编号,部门名称,获取部门列表方法,查找部门名称方法等)*/
export const useDepartment = () => {// 定义响应式变量// 部门列表const departmentList = ref<SelectOptions[]>([]);// 获取部门列表const fetchDepartmentList = async () => {let result = await departmentOptionsService();departmentList.value = result.data;};// 通过部门编号查找部门名称const lookupDepartmentName = (departmentNo: string) => {// 根据 departmentNo 值获取部门对象const department = departmentList.value.find((item) => item.value === departmentNo);// 返回部门名称return department ? (department.label as string) : "";};// 重置数据const resetData = () => {departmentList.value = [];};onMounted(async () => {// 获取部门列表await fetchDepartmentList();});onUnmounted(() => {// 重置数据resetData();});// 返回状态return { departmentList, fetchDepartmentList, lookupDepartmentName };
};

2、使用 Hooks,开箱即用

在组件 PurchaseChooseDialog.vue 中使用

<script setup lang="ts" name="PurchaseChooseDialog">
......
// 导入部门 hooks
import { useDepartment } from "@/hooks/useDepartment";// 部门 hooks,实现开箱即用的效果,这里是开箱(通过 useDepartment 开箱),后面是即用
const departmentHooks = useDepartment();
......
</script><template>
......<el-table-column prop="no" label="申购单" width="200" header-align="left" show-overflow-tooltip><template #default="scope"><div>{{ scope.row.no }} {{ scope.row.handlerId }}</div><!-- 部门 hooks,实现开箱即用的效果,前面是开箱,这里是即用(使用 lookupDepartmentName) --><div>{{ departmentHooks.lookupDepartmentName(scope.row.deptId) }}</div></template></el-table-column>
......
</template>

3、应用效果,数据是部门编号,显示是部门名称

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词