VUE 3:V型帮手没有反应能力 [英] Vue 3: v-model helper is not reactive

查看:10
本文介绍了VUE 3:V型帮手没有反应能力的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

帮助者:

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>

推荐答案

如果您不将道具传递给帮助器,它将不会跟踪计算属性中道具的更改。

将道具而不是pros.Model Value传递给帮助器:

const inputVal = vModel(props, context);

更新帮助器:

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

这篇关于VUE 3:V型帮手没有反应能力的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆