沐雨辰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 oracle集群安装出bug
  • ¥15 关于#python#的问题:自动化测试
  • ¥20 问题请教!vue项目关于Nginx配置nonce安全策略的问题
  • ¥15 教务系统账号被盗号如何追溯设备
  • ¥20 delta降尺度方法,未来数据怎么降尺度
  • ¥15 c# 使用NPOI快速将datatable数据导入excel中指定sheet,要求快速高效
  • ¥15 再不同版本的系统上,TCP传输速度不一致
  • ¥15 高德地图2.0 版本点聚合中Marker的位置无法实时更新,如何解决呢?
  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题