沐雨辰feng 2019-11-06 19:46 采纳率: 100%
浏览 2204
已采纳

刚开始接触vuex,login.vue文件中this.$store.state.token,总是报错——无法解析$store

我想实现一个登录功能,在login.vue文件下面

if (this.$store.state.token) {
    that.$router.push('/');
    console.log(this.$store.state.token);
} else {
    that.$router.replace('/login');
}

这里的this.$store一直提示无法解析,可我该引入的都引入了呀,实在不知道为什么会出这种错误,望各位大神帮帮我

store.js文件

import Vue from 'vue';
import Vuex from 'vuex';

Vue.use(Vuex);
const state = {
  token: localStorage.getItem('token') ? localStorage.getItem('token') : '', //token
};
export default new Vuex.Store({
  state,
  getters: {
    getStorage(state) {
      if (!state.token) {
        state.token = JSON.parse(localStorage.getItem(key));
      }
      return state.token
    }
  },
  mutations: {
    setToken(state, token) {
      state.token = token.value;
      localStorage.setItem("token", token.token);
    },
    deleteToken(state) {
      state.token = "";
      localStorage.removeItem("token")
    }
  }
})

main.js

import store from './store';
//////////////////
//中间代码省略了
/////////////////
new Vue({
  el: '#app',
  store,
  router: router,
  render: h => h(App)
});

login.vue

  import {mapMutations} from 'vuex';

  export default {
    name: "login",
    data: function () {
      return {
        loginText: '用户登录',
        account: '',
        password: '',
        value: '',
        single: false
      };
    },
    methods: {
      ...mapMutations(['setToken']),
      doLogin: function () {
        $('#userinfo .error-note').removeClass('error-note-show');
        var user = {};
        user.username = this.account;
        user.password = this.password;
        const that = this;
        $.ajax({
          url: "http://localhost:9090/auth/login",
          type: "POST",
          contentType: "application/json",
          dataType: "text",
          data: JSON.stringify(user),
          success: function (data, status, xhr) {
            var token = xhr.getResponseHeader("token");
            that.setToken({token: token});
            that.$router.push({path: "/"});
            var storage = window.localStorage;
            console.log(storage.getItem("token"));
            if (this.$store.state.token) {
              that.$router.push('/');
              console.log(this.$store.state.token);
            } else {
              that.$router.replace('/login');
            }
          },
          error: function (res) {
            console.log("返回格式错误" + res);
          }
        });}
      },
    },
  };
  • 写回答

1条回答 默认 最新

  • dabocaiqq 2019-11-06 22:27
    关注
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制
  • ¥20 usb设备兼容性问题
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊
  • ¥15 安装svn网络有问题怎么办