Within a reusable component, my goal is to develop a simple function that creates proxies for props in order to bind them to child components. These proxies will maintain their own internal value and be initialized with the default prop value, which may be provided when instantiated in other Vue components.
Using the following code snippet as an example:
const props = defineProps({
customFilteringToggle: Boolean,
expanded: {
type: Array as PropType<string[]>,
default: []
},
modelValue: {
type: Array as PropType<unknown[] | T[]>,
default: []
},
page: {
type: Number,
default: 1
}
});
const emit = defineEmits<{
(e: 'update:customFilteringToggle', value: boolean): void,
(e: 'update:expanded', value: any): void,
(e: 'update:modelValue', value: unknown): void
(e: 'update:page', value: number): void
}>();
/**************** Internal Properties ****************/
const createProxy = <T>(prop: () => T, event: string) => {
const _internal = ref(prop()) as Ref<T>;
watch(prop, value => _internal.value = value);
return computed({
get: () => _internal.value,
set: value => {
emit(event, value); // <--- throws error on `event` 'Vue: No overload matches this call.'
_internal.value = value;
}
});
};
const model = createProxy(() => props.modelValue, 'update:modelValue');
const expanded = createProxy(() => props.expanded, 'update:expanded');
const page = createProxy(() => props.page, 'update:page');
const showCustomFiltering = createProxy(() => props.customFilteringToggle, 'update:customFilteringToggle');
Is it possible to derive a list of events from:
const emit = defineEmits<{
(e: 'update:customFilteringToggle', value: any): void,
(e: 'update:expanded', value: any): void,
(e: 'update:modelValue', value: unknown): void
(e: 'update:page', value: number): void
}>();
This way, when the function is called, a suggested list of events can be generated without causing errors when providing the value as text. I often utilize keyof
for similar tasks, but this scenario seems more complex; if feasible at all.
If possible, I would prefer to avoid casting.