随着TS 5.1中发布的Variant Accessors,我希望能够创建像这样的可合成对象
export function useRouteQueryParam(param: MaybeRef<string>): WritableComputedRef<string | null>
export function useRouteQueryParam(param: MaybeRef<string>, defaultValue: string): WritableComputedRef<string>
export function useRouteQueryParam(param: MaybeRef<string>, defaultValue?: string): WritableComputedRef<string | null> {
const paramRef = ref(param)
const route = useRoute()
const router = useRouter()
return computed({
get() {
const [value] = asArray(route.query[paramRef.value])
return value ?? defaultValue ?? null
},
set(value) {
const query = { ...route.query, [paramRef.value]: value }
router.push({ query })
},
})
}
理论上,当调用者提供defaultValue
时,它可以为WritableComputedRef
使用不同的访问器。get总是返回string
,但set仍然应该接受string | null
。然而,因为WritableComputedRef
的语法只需要一个T
,我猜这还不可能实现?
1条答案
按热度按时间nxagd54h1#
https://tsplay.dev/wea0ew