静默之城
第一次感觉到危险离我们这么近
在Vue项目中,经常需要对Loading状态进行管理以提升用户体验。本文将介绍如何使用Vue自定义Hooks实现Loading状态的控制,并提供了一个名为useLoading的自定义Hook,能够方便地管理Loading状态。
          // 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
    }
}
        
      useLoading函数返回了一个对象,其中包含了state、start、stop和promise四个方法。state使用了readonly将initValue变为只读,以确保外部无法直接修改Loading状态。start方法将Loading状态设置为true,表示开始Loading。stop方法将Loading状态设置为false,表示结束Loading。promise方法接受一个Promise对象,当执行Promise时,会自动将Loading状态设置为true,并在Promise执行完毕后将Loading状态设置为false。useLoading可以在项目的任何地方使用,提高了代码的复用性。通过这样的封装,我们可以更加方便地管理Vue项目中的Loading状态,提升用户体验,减少重复代码的编写。
          <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>