vueHelper.ts 1005 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. import {
  2. watch,
  3. computed,
  4. WatchSource,
  5. getCurrentInstance,
  6. onMounted,
  7. onUnmounted,
  8. nextTick,
  9. reactive,
  10. ComponentInternalInstance,
  11. } from 'vue';
  12. export function explicitComputed<T, S>(source: WatchSource<S>, fn: () => T) {
  13. const v = reactive<any>({ value: fn() });
  14. watch(source, () => (v.value = fn()));
  15. return computed<T>(() => v.value);
  16. }
  17. export function tryOnMounted(fn: () => void, sync = true) {
  18. if (getCurrentInstance()) {
  19. onMounted(fn);
  20. } else if (sync) {
  21. fn();
  22. } else {
  23. nextTick(fn);
  24. }
  25. }
  26. export function tryOnUnmounted(fn: () => Promise<void> | void) {
  27. getCurrentInstance() && onUnmounted(fn);
  28. }
  29. export function tryTsxEmit<T extends any = ComponentInternalInstance>(
  30. fn: (_instance: T) => Promise<void> | void
  31. ) {
  32. const instance = getCurrentInstance() as any;
  33. instance && fn.call(null, instance);
  34. }
  35. export function isInSetup() {
  36. if (!getCurrentInstance()) {
  37. throw new Error('Please put useForm function in the setup function!');
  38. }
  39. }