我正在使用以下登录组件:
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
}
});
}
}
});
登录 API 返回一个 token 字符串以表示身份验证成功。我应该将它存储在全局变量还是本地存储中?是否有任何过滤器可用于检查用户是否已登录到应用程序,然后进行相应的重定向?
最佳答案
最好的方法是使用 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');
}
}
})
现在在您的组件 > 方法 > login() 中,您可以按如下方式分派(dispatch)您在 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');
}
}
});
这样做的好处:
你有一个集中状态,你可以在其中管理状态中的用户信息
您可以使用 vuex- persisted state 将状态保存在本地存储或作为 cookie如下所示,这将保存您的用户状态,包括 webtoken,甚至页面刷新时也会保留该状态。这意味着当用户登录并刷新页面时,由于存储中的用户状态被保留,您可以访问 webtoken 并使用户保持登录状态。
const store = new Store({
//...
插件:[ createPersistedState({
getState: (key) => Cookies.getJSON(key),
setState: (key, state) => Cookies.set(key, state, { 过期: 3, secure: true })
}) ]
})
您可以将 vuex 持久状态插件添加到您的商店,并使用 jscookies 库将用户状态保存在 cookie 中,或者如果您愿意,可以按照 vuex-persistedstate documentation 将用户状态保存在本地商店中。
关于javascript - 在 Vue JS 中处理登录 API token ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43581958/