Vue 3:v-model 助手不是反应式的

Vue 3: v-model helper is not reactive

我自己写了一个vue 3 v-model绑定的小帮手。奇怪的是它不能完全反应。内部更改以正确的方式发出,外部更改未被识别。但是,如果我在我的组件中使用相同的计算函数,一切都会按预期进行。 如何编写助手,使其完全反应?

帮手:

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

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

证监会:

<template>
    <div class="ms-deleteInput">
        <input class="ms-deleteInput__input" :label="label" v-model="inputVal" />
        <button @click="$emit('delete')" />
    </div>
</template>

<script lang="ts">
import { defineComponent, computed } from 'vue';

export default defineComponent({
    name: "deleteInput",
    props: {
        modelValue: {
            type: String,
            required: true,
        },
        label: {
            type: String,
            required: true,
        },
    },
    setup(props, context) {

        // This works
        const inputVal = computed({
            get: () => props.modelValue,
            set: (value) => {
                context.emit(`update:modelValue`, value);
            },
        });

        // This works, but external changes of modelValue prop will not be detected:
        const inputVal = vModel(props.modelValue, context);

        return {
            inputVal,
        };
    },
});
</script>

如果您不将 props 传递给 helper,它不会跟踪计算中的 props 变化 属性。

将 props 而不是 props.modelValue 传递给助手:

const inputVal = vModel(props, context);

更新助手:

export const vModel = (props, binding) =>
computed({
    get: () => props.modelValue,
    set: (value) => {
        context.emit(`update:${binding}`, value);
    },
});

感谢您的回答! 它现在适用于此:

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 文档中找不到好的输入方式。