【问题标题】:Where i may put authorization logic in vue.js?我可以在 vue.js 中将授权逻辑放在哪里?
【发布时间】:2019-08-11 17:45:18
【问题描述】:

我为 firebase 创建授权组件。并且发现了很多关于如何创建授权服务的帖子,该帖子的大部分内容是关于创建一些全局 const 或非常有趣的方式 - 使用 auth 方法创建 vue 插件。

但是当我自己做时,我很容易在 vuex 中创建 Auth 模块,并在创建 app.vue 生命周期时调用操作以检查用户并将该数据传递到存储中。

Post 在 vue 插件中创建身份验证时。

还有我的解决方案

import {VuexModule, Module, Mutation, Action} from 'vuex-module-decorators'
import * as firebase from 'firebase';
import { SingUpActionPayload, ResponseError, SingUpMutationPayload} from "./interfaces/singUp";

@Module
export default class Auth extends VuexModule {
    singUpData: any;
    singUpError: ResponseError = {
        code: '',
        message: ''
    };

    @Action({rawError: true})
    async singUp (payload: SingUpActionPayload) {
        try {
            let result = firebase.auth().createUserWithEmailAndPassword(payload.email, payload.password);
            await result;
            this.context.commit('setCurrentUser', firebase.auth().currentUser);
            this.context.commit('setSingUpResult', {type: 'result', result});
        } catch (error) {
            this.context.commit('setSingUpResult', {type: 'error', error});
        }
    }


    @Mutation
    setSingUpResult(payload: any){
        if(payload.type === 'result'){
            this.singUpData = payload.result;
        } else {
            this.singUpError = payload.error;
        }

    }

}



@Module
export default class UserModule extends VuexModule {
    currentUser = null;

    @Action({commit: 'setCurrentUser'})
    takeCurrentUser(){
        return  firebase.auth().currentUser;
    }

    @Mutation
    setCurrentUser(payload: any){
        this.currentUser = payload;
    }

}

对于路由器,我有类似帖子中的逻辑,只需从状态中检查用户。

所以现在我有一个问题,什么方式更好,带有身份验证服务或 vuex 模块的 vue 插件?

【问题讨论】:

    标签: vue.js vuejs2 vuex


    【解决方案1】:

    在您的案例中存在三个不同的工件:Vue 插件Auth ServiceVuex 模块!!!

    认证服务

    您需要身份验证服务来抽象您的 Authorization Server(Firebase) API。 Auth 服务应该不具备 DOM 或 Store 的知识。它严格处理网络层。

    Vuex 商店

    如果您需要在应用程序的不同视图/组件中提供身份验证数据,那么您应该在 store 中维护身份验证数据。因此,您的路由器或组件将与 Vuex 商店 通信,后者又通过商店 actionsAuth Service 通信。

    Vue 插件

    现在,这变得有趣了。如果您有多个(和单页)应用程序需要类似的功能,并且它们是不同的包或维护在不同的存储库中,那么插件是共享这种可重用逻辑的最佳方式。另外,如果你的代码需要做any of the following,那么你需要一个插件:

    • 添加一些全局方法或属性
    • 添加一个或多个全局资产:指令/过滤器/转换
    • 通过全局 mixin 添加一些组件选项。
    • 通过将一些 Vue 实例方法附加到 Vue.prototype 来添加它们。
    • 一个提供自己的 API 的库,同时注入上述的某种组合。

    由于您的 Vuex 商店可以通过操作处理身份验证,因此您可能不需要插件。

    就在此身份验证数据之上运行的实用功能而言,您可以简单地使用标准 ES 模块,而不是包装然后使用 Vue.js 插件

    【讨论】:

      猜你喜欢
      • 2012-01-22
      • 2016-03-08
      • 2018-06-24
      • 1970-01-01
      • 2014-03-16
      • 1970-01-01
      • 2011-03-12
      • 1970-01-01
      • 2013-07-26
      相关资源
      最近更新 更多