import { getCurrentInstance, ref, watch } from "vue";

export const useVModel = <T extends Record<string, any>, K extends keyof T>(
  props: T,
  key: K = "modelValue" as K
) => {
  const instance = getCurrentInstance();
  const prop = ref<T[K]>(props[key]);
  const event = `update:${key as string}`;
  if (instance) {
    watch(
      () => props[key],
      () => {
        prop.value = props[key];
      },
      { deep: true }
    );
    const emits = instance.emit;
    watch(
      prop,
      (v) => {
        emits(event, v);
      },
      { deep: true }
    );
  }
  return prop;
};
