vueHelper.ts 924 B

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