Created
September 14, 2023 10:50
-
-
Save LittleSaya/4d4d304bd0817d9329a4593b9413e5a6 to your computer and use it in GitHub Desktop.
vue 3.0 wait ref
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Ref, watch } from 'vue'; | |
const waitRefPredicateNonNullable = <T>(r: Ref<T>) => r.value !== null && r.value !== undefined; | |
/** | |
* 等待一个 ref 的值变为指定值 | |
* @param r | |
* @param predicate 判断 ref 值是否符合条件的函数 | |
*/ | |
export function waitRef<T>(r: Ref<T>, predicate: (r: Ref<T>) => boolean): Promise<Ref<T>> { | |
return new Promise((resolve) => { | |
if (predicate(r)) { | |
resolve(r); | |
return; | |
} | |
const unwatch = watch( | |
r, | |
() => { | |
if (predicate(r)) { | |
unwatch(); | |
resolve(r); | |
} | |
}, | |
{ | |
flush: 'post', | |
}, | |
); | |
}); | |
} | |
/** | |
* 等待一个 ref 的值变为非空,主要用于模态对话框打开时的初始化操作 | |
* @param r | |
*/ | |
export function waitRefExist<T>(r: Ref<T>): Promise<Ref<NonNullable<T>>> { | |
return waitRef(r, waitRefPredicateNonNullable) as Promise<Ref<NonNullable<T>>>; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment