前言
借助useLoading介绍一下react-hooks在定义更新数据的优势,也为后续vue组合式APIuse函数的封装打个预防针
介绍
useLoading本身并无太大的意义,但其却体现了一种很好的思想,继续往下看
基础使用
import useLoading from './useLoading'
const { loading, checkLoading } = useLoading()
// 开启loading
checkLoading(true)
// 关闭loading
checkLoading(false)
和react-hooks比较
和react-hooks做一下比较会发现使用极其的相似,但react更新数据的只能通过checkLoading,而vue除了checkLoading外还可以通过直接给loading赋值改变loading,如:loading.value = true,这让vue更新数据相对灵活,但也恰恰是这点让vue丢失了严谨性,这里更推荐react-hooks更新数据的方式
import { useState } from 'react'
const [loading, checkLoading] = useState(false)
// 开启loading
checkLoading(true)
// 关闭loading
checkLoading(false)
checkLoading更新数据的优势
1. 更新入口明确
checkLoading就是唯一更新方法
2. 保证的数据的流动、更新为正向而非逆向
loading.value = true就是对数据的逆向操作
后续将会有很多此类更新数据的方式,这里提前介绍一下
源码
// loading 状态
import { ref } from '@vue/composition-api'
export default () => {
const loading = ref(false)
// loading切换
const checkLoading = (value) => { loading.value = value }
return {
loading,
checkLoading
}
}
出参
| 参数 | 说明 | 类型 | 可选值 | 默认值 |
|---|---|---|---|---|
| loading | loading状态 | Booleab | - | false |
| checkLoading | 更新loading | Function | - | - |