我想实现一个登录功能,在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);
}
});}
},
},
};