[Vuejs]-How to access a component function from main.js in Vue 3 with Composition API

0👍

I finally ended up exposing the function in the mounted hook like this:

onMounted(() => {
  window.myWidget = {
    load: retrieveEndUserJWT,
  };
  retrieveDataAttributes();
  callWebsocket(websocket.value);
});

Then inside the same component, I create a method that will process the callback:

const retrieveEndUserJWT = async (endUserRetrievingTokenCallback) => {
  const jwt = await endUserRetrievingTokenCallback();
  processingToken(jwt);
};

And in the processingToken method, I deal with that token coming from the end-user callback function. I still have to navigate the pros and cons of exposing the function in the mounted hook.

0👍

main.js is meant for setting up your Vue application. Don’t use this for any other code! It won’t work.
Simply create a separate .js file (e.g. utils.js) and export the function from there.

I’m not completely sure what you’re trying to achieve exactly but it looks like an authentication process for logging in. What you’re probably trying to do is call the login/logout functions from within a Vue component? This could be as simple as

// Separate file, e.g. `authentication.js`
export const login = (cb) => {
  // do not name the callback function (cb) 'callback' as that may get you unexpected behavior
  // Your code
  somePromise().then((res) => {
    cb(res);
  });
}
// Your component
import { login } from 'path/to/authentication';

login(myCallback);

const myCallback = (res) => {
 ...
};

Leave a comment