vue3.0实现类似react-hooks的功能
写过react的都知道hooks用着非常顺手,所有的状态、行为啥的都可以使用hooks直接导出使用,而且还能根据state的变化触发视图更新,总之非常的方便快捷。所以在vue里面实现与react-hooks一样的功能,那么会使得vue开发变得一样畅快淋漓!!!
以下是我按照vue官网模拟了react-hooks一样的钩子函数(用于处理人对文件的权限,store用的是pinia):
定义hooks:
import { getBtnAuth } from '@/utils/utils'
import { FILE } from '@/db/const'
import { reactive, watch } from 'vue'
import { useShareStore, useGlobalStore } from '@/store'
import { FileInfo } from '@/types/share'
interface UseAuthData {
canIShare: boolean
canIDownload: boolean
canIAddFileCopy: boolean
canIMove: boolean
canIDelete: boolean
canIRename: boolean
canIEdit: boolean
canIReviewHistory: boolean
canIManageCooper: boolean
canIShareOutWay: boolean
isOwner: boolean
canIUploadVersion: boolean
canIRead: boolean
}
const useAuth = (file?: FileInfo) => {
const shareStore = useShareStore()
const globalStore = useGlobalStore()
let useAuthData = reactive({}) as UseAuthData
const handleValue = (fileInfo) => {
const FILE_ACTION_BITS = FILE.ACTION_BITS
const actions = fileInfo?.actions
const canIShare: boolean = getBtnAuth(actions, FILE_ACTION_BITS.SHARE)
const canIDownload: boolean = getBtnAuth(actions, FILE_ACTION_BITS.DOWNLOAD)
const canIAddFileCopy: boolean = getBtnAuth(actions, FILE_ACTION_BITS.COPY)
const canIMove: boolean = getBtnAuth(actions, FILE_ACTION_BITS.MOVE)
const canIDelete: boolean = getBtnAuth(actions, FILE_ACTION_BITS.DELETE)
const canIRename: boolean = getBtnAuth(actions, FILE_ACTION_BITS.RENAME)
const canIEdit: boolean = getBtnAuth(actions, FILE_ACTION_BITS.UPLOADVERSION)
const canIReviewHistory: boolean = getBtnAuth(actions, FILE_ACTION_BITS.LIST_ALL_VERSION)
const canIManageCooper: boolean = getBtnAuth(actions, FILE_ACTION_BITS.RESHARE)
const canIShareOutWay: boolean = !globalStore.query('enterprise').forbidShareOut
const isOwner: boolean = fileInfo?.ownerId === globalStore.query('user').userId
const canIUploadVersion: boolean = getBtnAuth(actions, FILE_ACTION_BITS.UPLOADVERSION)
const canIRead: boolean = getBtnAuth(actions, FILE_ACTION_BITS.READ)
useAuthData = Object.assign(useAuthData, {
canIShare,
canIDownload,
canIAddFileCopy,
canIMove,
canIDelete,
canIRename,
canIEdit,
canIReviewHistory,
canIManageCooper,
canIShareOutWay,
isOwner,
canIUploadVersion,
canIRead,
})
}
watch(
() => shareStore.fileInfo,
(fileInfo) => {
handleValue(fileInfo)
},
{
immediate: true,
deep: true,
}
)
if (file) {
handleValue(file)
}
return useAuthData
}
export default useAuth
使用hooks
import useAuth from '@/hooks/useAuth'
// useAuthData整个对象它是响应式的,可以在模板里随意使用,数据与视图响应式更新。
const useAuthData = useAuth()
核心思想:
- 定义一个reactive对象用于hooks返回,使得返回的这个对象是“响应式”的;
- 使用watch监听状态管理中数据,数据变更调用handleValue 将更新的值带入重新计算并赋值给reactive对象,触发响应式更新。
- useAuth()可以传入一个文件对象,也可主动触发文件权限响应式更新;
949

被折叠的 条评论
为什么被折叠?



