tryOnMounted.js 499 B

123456789101112
  1. // eslint-disable-next-line no-restricted-imports
  2. import { getCurrentInstance, nextTick, onMounted } from 'vue';
  3. /**
  4. * Call onMounted() if it's inside a component lifecycle, if not, just call the function
  5. *
  6. * @param fn
  7. * @param sync if set to false, it will run in the nextTick() of Vue
  8. */
  9. export function tryOnMounted(fn) {
  10. let sync = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
  11. if (getCurrentInstance()) onMounted(fn);else if (sync) fn();else nextTick(fn);
  12. }