Understanding a variable that is outside an export within an imported file

感情迁移 提交于 2020-08-10 19:11:50

问题


Auth0 has some great documentation for its new javascript sdk to be used with Vue. See the Vue Quickstart page.

I'm confused by something they do with a variable that is outside the "export" of an imported module. Where does the instance variable live? Is it a global variable? Is it only available to the imported file itself?

If you import this module multiple times, I'd think it would run the let instance each time.

I must be misunderstanding how import works.

src/auth/index.js

import Vue from "vue";
import createAuth0Client from "@auth0/auth0-spa-js";

/** Define a default action to perform after authentication */
const DEFAULT_REDIRECT_CALLBACK = () =>
  window.history.replaceState({}, document.title, window.location.pathname);

let instance;

/** Returns the current instance of the SDK */
export const getInstance = () => instance;

/** Creates an instance of the Auth0 SDK. If one has already been created, it returns that instance */
export const useAuth0 = ({
  onRedirectCallback = DEFAULT_REDIRECT_CALLBACK,
  redirectUri = window.location.origin,
  ...options
}) => {
  if (instance) return instance;

  // The 'instance' is simply a Vue object
  instance = new Vue({
    data() {
        ...
    },
    methods: {
        ...
    } 
  });

  return instance;
};

// Create a simple Vue plugin to expose the wrapper object throughout the application
export const Auth0Plugin = {
  install(Vue, options) {
    Vue.prototype.$auth = useAuth0(options);
  }
};

来源:https://stackoverflow.com/questions/63125529/understanding-a-variable-that-is-outside-an-export-within-an-imported-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!