vuex commit state的值没改变

正常情况用户登录成功将token保存在localstorage中,登陆成功了但是localstorage中没token信息

后端返回的token:
clipboard.png

token为null

clipboard.png

login.vue

import axios from 'axios'
import store from '@/vuex/store'
import * as types from '@/vuex/types'

submitForm(formname) {
    var _this = this;
    this.$refs[formname].validate((valid) => {
        if (valid) {
            axios.post('/api/users', {
                username: this.form.email,
                password: this.form.password,
                action: 'login'
            })
            .then(function(res){
                store.commit('types.LOGIN', res['data']);
                console.log(store);
                _this.$router.push('/dashboard');
            })
            .catch(function(err){
                console.log(err);
                _this.noticeBox('用户名或密码不正确');
            });
        }else{
            console.log('error submit!!');
            return false;
        }
    });
},

store.js

import Vue from 'vue'
import Vuex from 'vuex'
import * as types from './types'

Vue.use(Vuex);

const state = {
    user: {},
    token: null,
    title: ''
}

const mutations = {
    [types.LOGIN]: (state, data) => {
        localStorage.token = data;
        state.token = data;
    },
    [types.LOGOUT]: (state) => {
        localStorage.removeItem('token');
        state.token = null;
    }
}

export default new Vuex.Store({
    state,
    mutations
})
阅读 5.6k
2 个回答
// 这句写错了。'types.LOGIN'不应该是这样写的字符串。
store.commit('types.LOGIN', res['data']);
// 所以这个代码没执行。
// types.LOGIN 猜测这个应该是`login`。
[types.LOGIN]: (state, data) => {
    localStorage.token = data;
    state.token = data;
},

感谢评论指出,我的答案是错误的,请忽略

你的localStorage的用法错了存数据应该localStorage.setItem('token', '你的要存的token')
获取数据localStorage.getItem('token'),删除数据localStorage.removeItem('token');

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进