vue3 Hooks 封装loading使用
个人理解:Hooks 就是 钩子 的意思,在特定时机执行的函数
之前不理解Hooks和自定义封装的utils函数有什么区别,它们都是函数,逐步理解到utils函数没有vue里面的响应式api,而自定义Hooks可以使用响应式api,比如:ref、reactive、onMounted等等
举例说明:
loading大家都不陌生,在项目请求接口时需要显示loading加载提示用户正在请求中的操作,在加载完成隐藏loading,显示返回的数据。
下面使用vue3 Hooks 来封装这个业务场景
定义 Hooks 有一个潜规则,就是要 use 开头
            
            
              bash
              
              
            
          
          // useLoading.ts
import { ref } from 'vue'
export const useLoading = () => {
    const loading = ref(false)
    const show = () => {
        loading.value = true
    }
    const hide = () => {
        loading.value = false
    }
    
    return {
        loading,
        hide,
        show
    }
}我这里用的elementui框架,使用v-loading绑定loading变量
            
            
              bash
              
              
            
          
          <template>
    <div style="width: 300px;height: 300px;border: 1px solid #000" v-loading="loading">  </div>
    <el-button @click="show">显示loading</el-button>
    <el-button @click="hide">隐藏loading</el-button>
</template>
<script lang="ts" setup>
 import { useLoading } from '@/hooks/useLoading.ts'
 const { 
	loading,
	hide,
	show
	} = useLoading()
</script>使用Hooks是为了让项目整体的开发代码质量更加高,开发功能更加便捷,效率更高