UNPKG

@ark-ui/vue

Version:

A collection of unstyled, accessible UI components for Vue, utilizing state machines for seamless interaction.

52 lines (49 loc) 1.24 kB
import { getCurrentInstance, ref, watch, nextTick, computed } from 'vue'; 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; 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 initialValue = getValue(); const proxy = ref(initialValue); 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); } }); } export { useVModel };