Blame view

src/utils/helper/vueHelper.ts 1 KB
陈文彬 authored
1
2
3
4
5
6
7
8
9
import {
  watch,
  computed,
  WatchSource,
  getCurrentInstance,
  onMounted,
  onUnmounted,
  nextTick,
  reactive,
vben authored
10
  ComponentInternalInstance,
陈文彬 authored
11
} from 'vue';
vben authored
12
import { error } from '../log';
陈文彬 authored
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30

export function explicitComputed<T, S>(source: WatchSource<S>, fn: () => T) {
  const v = reactive<any>({ value: fn() });
  watch(source, () => (v.value = fn()));
  return computed<T>(() => v.value);
}

export function tryOnMounted(fn: () => void, sync = true) {
  if (getCurrentInstance()) {
    onMounted(fn);
  } else if (sync) {
    fn();
  } else {
    nextTick(fn);
  }
}

export function tryOnUnmounted(fn: () => Promise<void> | void) {
31
  getCurrentInstance() && onUnmounted(fn);
陈文彬 authored
32
33
}
vben authored
34
35
36
37
export function tryTsxEmit<T extends any = ComponentInternalInstance>(
  fn: (_instance: T) => Promise<void> | void
) {
  const instance = getCurrentInstance() as any;
38
  instance && fn.call(null, instance);
陈文彬 authored
39
40
41
42
}

export function isInSetup() {
  if (!getCurrentInstance()) {
vben authored
43
    error('Please put useForm function in the setup function!');
陈文彬 authored
44
45
  }
}