@ark-ui/vue
Version:
A collection of unstyled, accessible UI components for Vue, utilizing state machines for seamless interaction.
41 lines (40 loc) • 1.1 kB
JavaScript
import { computed, getCurrentInstance, nextTick, ref, watch } from "vue";
//#region src/components/use-v-model.ts
function useVModel(props, key, emit, options = {}) {
const { passive = false, eventName, defaultValue } = options;
const vm = getCurrentInstance();
const _emit = emit || vm?.emit || vm?.$emit?.bind(vm) || vm?.proxy?.$emit?.bind(vm?.proxy);
const prop = key || "modelValue";
const getValue = () => props[prop] ?? defaultValue;
const triggerEmit = (value) => {
if (!eventName) _emit(eventName || `update:${prop.toString()}`, value);
else for (const event of eventName) _emit(event, value);
};
if (passive) {
const proxy = ref(getValue());
let isUpdating = false;
watch(() => props[prop], (v) => {
if (!isUpdating) {
isUpdating = true;
proxy.value = v;
nextTick(() => {
isUpdating = false;
});
}
});
watch(proxy, (v) => {
if (!isUpdating && v !== props[prop]) triggerEmit(v);
});
return proxy;
}
return computed({
get() {
return getValue();
},
set(value) {
triggerEmit(value);
}
});
}
//#endregion
export { useVModel };