I created a small utility for handling vue 3 v-model binding, but I'm encountering an issue with reactivity. The internal changes are being emitted correctly, however, external changes are not being recognized. Interestingly, when I use the same computed function within my component, everything works as expected. How can I modify the utility to ensure full reactivity?
The utility:
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);
},
});
The single file component (sfc):
<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 too, but external changes of modelValue prop will not be detected:
const inputVal = vModel(props.modelValue, context);
return {
inputVal,
};
},
});
</script>