Skip to content

Instantly share code, notes, and snippets.

@epreston
Created April 28, 2023 19:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save epreston/79415482f15e55da25ad6527049bee1d to your computer and use it in GitHub Desktop.
Save epreston/79415482f15e55da25ad6527049bee1d to your computer and use it in GitHub Desktop.
vue - add app.mount lifecycle hooks - onBeforeMount and onAfterMount
// add app mount lifecycle hooks to the app instance for plugins to use when registering.
function addAppMountLifecycleHooks(app) {
const beforeHooks = [];
const afterHooks = [];
const boundMount = app.mount.bind(app);
app.mount = (async (rootContainer, isHydrate, isSVG) => {
for (const preHook of beforeHooks) await preHook(app);
boundMount(rootContainer, isHydrate, isSVG);
for (const postHook of afterHooks) await postHook(app);
afterHooks.length = beforeHooks.length = 0;
}).bind(app);
app.onBeforeMount = (hook, remove = false) => {
remove ? beforeHooks.unshift(hook) : beforeHooks.push(hook);
};
app.onAfterMount = (hook, remove = false) => {
remove ? afterHooks.unshift(hook) : afterHooks.push(hook);
};
}
@epreston
Copy link
Author

Usage: used when creating the app instance to add hooks that custom plugins can use.

import { createApp } from 'vue';

// create and return vue app instance
export function createVueApp(rootComponent) {
  const app = createApp(rootComponent);

  // add onBeforeMount and onAfterMount methods
  addAppMountLifecycleHooks(app);

  app.config.errorHandler = (err, instance, info) => {
    // handle error, e.g. report to a service
    console.error(`Error: ${err.toString()}\nInfo: ${info}`);
  };

  app.config.warnHandler = (msg, instance, trace) => {
    // `trace` is the component hierarchy trace
    console.log(`Warn: ${msg}\nTrace: ${trace}`);
  };

  return app;
}

The methods added are:

app.onBeforeMount(hook, remove = false) 
app.onAfterMount(hook, remove = false)

Each hook is called with the current vue App instance either before or after.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment