继续完善登录状态管理功能

This commit is contained in:
高子兴 2024-06-30 17:36:44 +08:00
parent 2ee3f12888
commit a420b5d908
2 changed files with 43 additions and 38 deletions

View File

@ -1,30 +1,37 @@
const state = {
user: null
}
import { createStore } from 'vuex';
import axios from 'axios';
const mutations = {
const store = createStore({
state: {
user: null,
isAuthenticated: false,
},
mutations: {
setUser(state, user) {
state.user = user
state.user = user;
state.isAuthenticated = true;
},
clearUser(state) {
state.user = null;
state.isAuthenticated = false;
},
},
actions: {
async login({ commit }, credentials) {
const response = await axios.post('/api/login', credentials);
if (response.status === 200) {
commit('setUser', response.data.username);
}
}
const actions = {
login({ commit }, user) {
commit('setUser', user)
return response;
},
logout({ commit }) {
commit('setUser', null)
}
}
commit('clearUser');
},
},
getters: {
isAuthenticated: (state) => state.isAuthenticated,
user: (state) => state.user,
},
});
const getters = {
isAuthenticated: state => !!state.user
}
export default {
namespaced: true,
state,
mutations,
actions,
getters
}
export default store;

View File

@ -2,7 +2,11 @@
import { ref } from 'vue';
import { ElInput, ElButton, ElCheckbox, ElForm, ElFormItem, ElMessage } from 'element-plus';
import 'element-plus/dist/index.css';
import axios from 'axios';
import { useStore } from 'vuex';
import { useRouter } from 'vue-router';
const store = useStore();
const router = useRouter();
const username = ref('');
const password = ref('');
@ -12,26 +16,20 @@ const handleLogin = async () => {
console.log('Logging in with', { username: username.value, password: password.value, rememberMe: rememberMe.value });
try {
const response = await axios.post('/api/login', {
const response = await store.dispatch('login', {
username: username.value,
password: password.value,
});
if (response.status === 200) {
const data = response.data;
ElMessage.success(data.message);
// tokenVuex
localStorage.setItem('token', data.token);
//
// router.push('/home');
ElMessage.success('登录成功');
router.push('/profile');
} else {
// 200
ElMessage.error('登录失败,请稍后再试');
}
} catch (error) {
if (error.response && error.response.status === 401) {
const data = error.response.data;
ElMessage.error(data.message);
ElMessage.error('用户名或密码错误');
} else {
ElMessage.error('登录失败,请稍后再试');
}