vue2.0 vuex2.0的 神奇bug

2017-02-12  本文已影响185人  北方蜘蛛

import * as types from '../types'

import api from '../../api/Rest-api.js'

var isLoggedIn = function() {

var token = localStorage.getItem('user');

if (token) {

return JSON.parse(localStorage.getItem('user'))

} else {

return false;

}

}

const state = {

token: isLoggedIn() || null,

message: {

text: null,

css: null

},

user_login_info: isLoggedIn() || null

}

const getters = {

userLoginStatus: state => state.token ? '已登录' : '未登录',

userLoginMessage: state => state.message,

userLoginInfo: state => state.token

}

const mutations = {

[types.USER__VUEX_LOGIN](state, status = NaN) {

state.token = isNaN(status) ? !state.token : status

},

[types.USER__VUEX_lOGIN_INFO](state, info) {

state.user_login_info = info

},

[types.USER_SIGNIN](state, user) {

localStorage.setItem('user', JSON.stringify(user));

state.token = user

},

[types.USER_SIGNOUT](state) {

localStorage.removeItem('user');

state.token = null;

},

[types.USER_REG](state, user) {

localStorage.setItem('user', JSON.stringify(user));

state.token = user

},

[types.USER__VUEX_lOGIN_MESSAGE](state, status = NaN) {

state.message = status

},

}

const actions = {

userLoginAjax({ commit }, data) {

if (!data.userName || !data.password) {

commit(types.USER__VUEX_lOGIN_MESSAGE, { text: '请填写完整', css: 'error' });

return;

}

api.userlogin(JSON.stringify(data)).then(function(response) {

if (response.data.statusCode == 200) {

commit(types.USER__VUEX_lOGIN_MESSAGE, { text: '登陆成功', css: 'success' });

commit(types.USER_SIGNIN, response.data.result.user);

commit(types.USER__VUEX_LOGIN, true);

} else {

commit(types.USER__VUEX_lOGIN_MESSAGE, { text: '登陆失败', css: 'error' });

}

})

.catch(function(error) {

console.log(error);

});

},

userLogout({ commit }) {

api.get(api.logout.url).then(function(response) {

if (response.data.statusCode == 200) {

commit(types.USER_SIGNOUT);

}

})

.catch(function(error) {

console.log(error);

});

}

}

export default {

state,

getters,

actions,

mutations

}

先看着端代码,中括号的部分不是很理解,照猫画虎的就先用了。但是发现一个人气的bug在使用userLogonajx这个方法时,使用commit 把数据推到state中那个中括号里的types.USER__VUEX_lOGIN_MESSAGE 居然可以随意写生types.XXXX的任何东西镇的让我很费解,有时候还容易推到其他地方去,这种是bug还是有用的不对呢?

上一篇下一篇

猜你喜欢

热点阅读