在 Vue 应用程序中创建 class 的单个实例

Creating a single instance of a class within a Vue application

我是 Vue 的新手,我正在努力思考如何实现在我看来适合全局变量或单例的东西。

背景是我正在使用 Azure AD B2C 通过 MSAL 库进行身份验证。 MSAL 需要声明 Msal.UserAgentApplication 的单个实例,然后通过应用程序共享。

我正在苦苦挣扎的是如何在中央某处声明该实例,然后从包括路由器在内的每个组件访问它。

目前我有一个类似于此示例的 class:https://github.com/sunilbandla/vue-msal-sample/blob/master/src/services/auth.service.js 当我想使用我正在做的方法时:

var authService = new AuthService();
authService.Login();

不幸的是,每次实例化 class 时都会创建一个新的 MSAL 实例,这反过来导致我的用户最终陷入身份验证循环。

如有任何帮助,我们将不胜感激。

非常感谢。


根据 Teddy 的以下回答,我修改了我的 main.js 如下:

import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import './registerServiceWorker'
import AuthService from './services/AuthService';

Vue.config.productionTip = false

Vue.prototype.$authService = new AuthService();

new Vue({
  router,
  store,
  render: h => h(App)
}).$mount('#app');

而我的register.vue组件如下:

<template>
  <div class="about">
    <h1>This is the register page, it should redirect off to B2C</h1>
  </div>
</template>

<script>
  import router from '@/router.js'

  export default {

    created(){

      this.$authService.isAuthenticated().then(
      function(result){
        if(result){
          router.push('/');  
        }
        else{
          authService.register();  
        }
      });
    }  
  } 
</script>

组件说 this.$authService 未定义,所以它显然没有读取原型。

感觉此时我在 Vue 中缺少一些真正基础的东西。

您可以将其添加为 Vue 实例 属性。它适用于所有 Vue 组件。

在 main.js 中这样设置:

Vue.prototype.$authService = new AuthService();

您以后可以在任何 Vue 组件中访问它。例如:

this.$authService.Login();

参考: https://vuejs.org/v2/cookbook/adding-instance-properties.html

编辑: 您必须在 isAuthenticated 回调中使用 this.$router.push 和 this.$authService.register 。如果 "this" 引用该块中的其他内容,则存储 var self=this;在回调开始之前,或使用粗箭头语法。

<script>
  //No import as router is available in 'this'
  export default {

    created(){
      var self=this; //For use inside the callback
      this.$authService.isAuthenticated().then(
      function(result){
        if(result){
          self.$router.push('/');  
        }
        else{
          self.$authService.register();  
        }
      });
    }  
  } 
</script>

编辑 2:

也许您可以在名为 AuthServiceInst.js 的文件中创建实例(单例)本身。然后你可以在 main.js 和 router.js.

中导入它

新建文件AuthServiceInst.js:

import AuthService from './AuthService.js'

export const authService = new AuthService();

main.js:

import {authService} from './AuthServiceInst.js'

Vue.prototype.$authService = authService;

router.js:

import {authService} from './AuthServiceInst.js'

//Now you can use authService