简体   繁体   English

如何使用组合 API 从 Vue 3 中的 main.js 访问组件 function

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

Using Vue 3 and composition API I have a component that have this function:使用 Vue 3 和组合 API 我有一个组件有这个 function:

const retrieveSignedJWT = async (callback) => {
  if (jwtUrl.value && !callback) {
    //console.log("There's no callback use the by default URL")
    await fetch(jwtUrl.value)
      .then(async (response) => {
        const data = await response.text();
        // check for error response
        if (!response.ok) {
          // get error message from body or default to response statusText
          const error = (data && data.message) || response.statusText;
          return Promise.reject(error);
        }
        let jwt = data;
        token.value = data;
        decodeToken(jwt);
        retrieveCategories();
      })
      .catch((error) => {
        errorMessage.value = error;
        console.error("There was an error!", error);
      });
  } else {
    //Function has a callback
    token.value = callback;
  }
};

What I need to do is to find a way to expose the previous component function so I can call it from the main.js.我需要做的是找到一种方法来暴露之前的组件 function 以便我可以从 main.js 中调用它。 The scenario is that I'm creating an IIFFE with Vue 3 and Vite (a widget that the end user will load from a script) and hooking up a public function to it so the user can use it at any point in their code.场景是我正在使用 Vue 3 和 Vite(最终用户将从脚本加载的小部件)创建一个 IIFFE,并将公共 function 连接到它,以便用户可以在他们的代码中的任何位置使用它。 That function can have or not have a callback that will expose a token implemented.那个 function 可以有也可以没有回调来公开实现的令牌。

import { createApp } from "vue";
import "@/assets/styles/index.scss";
import App from "./App.vue";
import store from "./store";
let div = document.createElement("div");
document.body.appendChild(div);
div.setAttribute("id", "my-widget");
window.myWidget = {
  load: function (endUserRetrievedJWT) {
    if (endUserRetrievedJWT) {
      const endUserJWT = endUserRetrievedJWT();
      //Calling my component function w a call back
      retrieveSignedJWT(endUserJWT);
    } else {
      //Calling my component function without a call back 
      retrieveSignedJWT();
    }
  },
};
createApp(App).use(store).mount("#my-widget");

So basically I'm trying to find a way to invoke the parent component function from the main.js file in order to manage how to save a token to the state of my application.所以基本上我试图找到一种方法来从 main.js 文件调用父组件 function,以便管理如何将令牌保存到我的应用程序的 state。 That token can come from a default URL or in the shape of a callback function that the end-user will pass as an argument to the globally expose function coming from main.js.该令牌可以来自默认 URL 或回调 function 的形式,最终用户将作为参数传递给来自 main.js 的全局公开 function。

main.js is meant for setting up your Vue application. main.js 用于设置您的 Vue 应用程序。 Don't use this for any other code.不要将此用于任何其他代码。 It won't work.它不会工作。 Simply create a separate.js file (eg utils.js) and export the function from there.只需创建一个单独的 .js 文件(例如 utils.js)并从那里导出 function。

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?我不完全确定你到底想实现什么,但它看起来像是登录的身份验证过程。你可能想做的是从 Vue 组件中调用登录/注销功能? 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) => {
 ...
};

I finally ended up exposing the function in the mounted hook like this:我终于在挂钩中暴露了 function,如下所示:

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.在 processingToken 方法中,我处理来自最终用户回调 function 的令牌。我仍然需要了解在已安装的挂钩中公开 function 的利弊。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM