Words etch cherished moments.
OG

自定义Hooks实现Loading状态控制

1,977 words, 5 min read
2021/06/02 AM
274 views

在Vue项目中,经常需要对Loading状态进行管理以提升用户体验。本文将介绍如何使用Vue自定义Hooks实现Loading状态的控制,并提供了一个名为useLoading的自定义Hook,能够方便地管理Loading状态。

          
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
// src/hooks/useLoading.ts import { ref, readonly } from 'vue' export const useLoading = () => { const initValue = ref(false) // 设置开始状态 const start = () => { initValue.value = true } // 设置结束状态 const stop = () => { initValue.value = false } // 执行promise const promise = <T>(promise: Promise<T>) => { start() return promise.finally(() => { stop() }) } return { state: readonly(initValue), start, stop, promise } }

#代码讲解:

  1. useLoading函数返回了一个对象,其中包含了statestartstoppromise四个方法。
  2. state使用了readonlyinitValue变为只读,以确保外部无法直接修改Loading状态。
  3. start方法将Loading状态设置为true,表示开始Loading。
  4. stop方法将Loading状态设置为false,表示结束Loading。
  5. promise方法接受一个Promise对象,当执行Promise时,会自动将Loading状态设置为true,并在Promise执行完毕后将Loading状态设置为false

#优点:

  • 简洁易用:通过封装成Hook,使得在Vue组件中使用Loading状态变得非常简单。
  • 可复用性useLoading可以在项目的任何地方使用,提高了代码的复用性。
  • 封装性:将Loading状态管理的逻辑封装在一个独立的Hook中,使得代码更加清晰易懂,便于维护。
  • 响应式更新:通过Vue的响应式系统,Loading状态的变化能够自动更新到UI上,提升了用户体验。

通过这样的封装,我们可以更加方便地管理Vue项目中的Loading状态,提升用户体验,减少重复代码的编写。

#使用示例:

          
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
<template> <template v-if="loading.state.value"> 数据加载中 </template> <template v-else> <div v-for="item in list"> {{item.title}} </div> </template> </template> <script setup lang="ts"> import { useLoading } from '@/hooks/loading' import { getArticles } from '@/api/article' const list = ref([]) const loading = useLoading() /** * 获取数据 */ const fetchData = () => { // getArticles 方法为 api 请求 loading.promise(getArticles).then((res) => { console.log(res, '数据加载完成') list.value = res.data }) } </script>
Published at2021/06/02 AMinCode
#Vue
Creative Commons BY-NC 4.0
https://zhangwurui.cn/article/74
0/0comments
Guest
Start the discussion...
Be the first to comment