useMergedState.js 1.1 KB

1234567891011121314151617181920212223242526272829303132333435
  1. import { toRaw, watchEffect, unref, watch, ref } from 'vue';
  2. export default function useMergedState(defaultStateValue, option) {
  3. const {
  4. defaultValue,
  5. value = ref()
  6. } = option || {};
  7. let initValue = typeof defaultStateValue === 'function' ? defaultStateValue() : defaultStateValue;
  8. if (value.value !== undefined) {
  9. initValue = unref(value);
  10. }
  11. if (defaultValue !== undefined) {
  12. initValue = typeof defaultValue === 'function' ? defaultValue() : defaultValue;
  13. }
  14. const innerValue = ref(initValue);
  15. const mergedValue = ref(initValue);
  16. watchEffect(() => {
  17. let val = value.value !== undefined ? value.value : innerValue.value;
  18. if (option.postState) {
  19. val = option.postState(val);
  20. }
  21. mergedValue.value = val;
  22. });
  23. function triggerChange(newValue) {
  24. const preVal = mergedValue.value;
  25. innerValue.value = newValue;
  26. if (toRaw(mergedValue.value) !== newValue && option.onChange) {
  27. option.onChange(newValue, preVal);
  28. }
  29. }
  30. // Effect of reset value to `undefined`
  31. watch(value, () => {
  32. innerValue.value = value.value;
  33. });
  34. return [mergedValue, triggerChange];
  35. }