编写一个简易版useVModel

    1. export interface VModelOptions<T> {
    2. eventName?: string
    3. }
    4. function useVModel<P extends object, K extends keyof P, Name extends string>(props: P, key?: K, emit?: (name: Name, ...args: any[]) => void, options: VModelOptions<P[K]> = {},) {
    5. const {
    6. eventName
    7. } = options
    8. // 获取当前实例
    9. const vm = getCurrentInstance()
    10. const _emit = emit || vm?.emit
    11. if (!key) key = 'modelValue' as K
    12. let event = eventName || `update:${String(key)}`
    13. return computed<P[K]>({
    14. get() {
    15. return props[key as K]
    16. },
    17. set(value) {
    18. _emit && _emit(event as Name, value)
    19. }
    20. })
    21. }
    22. export default useVModel