在Vue JS中处理登录API令牌

Viv*_*adh 7 javascript vue.js vuejs2

我正在使用以下Login组件:

var Login = Vue.extend({
    template: '#auth',
    data: function () {
        return {username: '',password: '',errorMessage:''};
    },
    methods : {
        login: function (e) {
            var _this = this;
            $.ajax({
                url: "/vue/api/login",
                type: "POST",
                async:false,
                data:{
                    username:_this.username,
                    password: _this.password
                },
                success: function (data) {
                // store the token in global variable ??
                    router.push({
                        path: '/employeeList',
                    });
                },
                error:function (xhr, status, error) {

                    _this.errorMessage = xhr.responseText
                }
            });
        }
    }
});
Run Code Online (Sandbox Code Playgroud)

登录API返回令牌字符串以便成功进行身份验证.我应该将它存储在全局变量还是本地存储中?是否有任何过滤器可用于检查用户是否登录到应用程序然后相应地重定向?

Vam*_*hna 8

最好的方法是使用VUEX:一个vue状态管理系统

在vuex store.js文件中,您可以按如下方式定义用户的状态:

const store = new Vuex.Store({ 
    state: { 
        user: {
            userName:'',
            loggedInStatus: true,
            authToken: ''
        }
    }, 
    mutations: { 
        addWebToken: function(state, webToken){
            state.user.authToken = webToken;
        },
        removeWebToken: function(state){
            state.user.authToken = '';
        }
    },
    actions: {
        login: function(context, userInput){
            $.ajax({
                url: "/vue/api/login",
                type: "POST",
                async:false,
                data:{
                    username:userInput.username,
                    password: userInput.password
                },
                success: function (data) {
                // store the token in global variable ??

                context.commit('addWebToken', webToken); // pass the webtoken as payload to the mutation

                    router.push({
                        path: '/employeeList',
                    });
                },
                error:function (xhr, status, error) {

                    _this.errorMessage = xhr.responseText
                }
            });
        },
        logput: function(context){
            //your logout functionality
            context.commit('removeWebToken');
        }
    }

})
Run Code Online (Sandbox Code Playgroud)

现在在您的组件> methods> login()中,您可以调度您在vuex srore中声明的登录操作,如下所示

var Login = Vue.extend({
        template: '#auth',
        data: function () {
            return {username: '',password: '',errorMessage:''};
        },
        methods : {
            login: function () {
                //passing the username and password in an object as payload to the login action
                this.$store.dispatch('login', {username: this.username, ppassword: password});
            },
            logout: function(){
                this.$store.dispatch('logout');
            }
        }
    });
Run Code Online (Sandbox Code Playgroud)

这样做的好处:

  • 您有一个集中状态,您可以在其中管理州内的用户信息

  • 您可以使用vuex-persisted状态将状态保存在本地存储中或作为cookie 保存,如下所示,这将保存用户的状态,包括webtoken,甚至状态也会在页面刷新时保留.这意味着当用户登录并刷新页面时,由于保留了来自商店的用户状态,因此您可以访问webtoken并保持用户登录.

const store = new Store({ // ... plugins: [ createPersistedState({ getState: (key) => Cookies.getJSON(key), setState: (key, state) => Cookies.set(key, state, { expires: 3, secure: true }) }) ] })

您可以将vuex持久状态插件添加到您的商店,并使用jscookies库将您的用户状态保存在cookie中,或者如果您愿意,可以按照vuex-persistedstate文档保存本地存储