首页 > 解决方案 > Vue 3:v-model 助手类型

问题描述

在使用Vue 3 中提供的帮助使 v-model 助手工作后:v-model 助手不是反应式的,它现在可以使用:

import { computed, SetupContext, WritableComputedRef } from 'vue';

export const vModel = <T>(props: Record<string, T>, context: SetupContext, binding = 'modelValue'): WritableComputedRef<T> =>
    computed({
        get: () => props[binding],
        set: (value) => {
            context.emit(`update:${binding}`, value);
        },
    });

但打字不正确。我得到错误:

Argument of type 'Readonly<LooseRequired<Readonly<{ modelValue?: unknown; label?: unknown; } & { modelValue: string; label: string; } & {}> & { [x: string & `on${string}`]: undefined; }>>' is not assignable to parameter of type 'Record<string, string>'.
  'string & `on${string}`' and 'string' index signatures are incompatible.
    Type 'undefined' is not assignable to type 'string'.

我在函数内尝试了几种类型props,但它们似乎都不正确。我在 vue 文档中找不到输入的好方法。

标签: typescriptvue.jsvuejs3vue-composition-api

解决方案


推荐阅读