// store/index.js - Vuex状态管理配置文件
import { createStore } from 'vuex'
import axios from 'axios'
// 创建状态存储实例
export default createStore({
// 状态 - 存储应用的全局状态
state: {
// 用户信息
user: JSON.parse(localStorage.getItem('user')) || null,
token: localStorage.getItem('token') || null,
// 帖子相关
posts: [],
currentPost: null,
// 分类相关
categories: [
{ id: 1, name: '综合讨论' },
{ id: 2, name: '技术交流' },
{ id: 3, name: '问题求助' },
{ id: 4, name: '经验分享' },
{ id: 5, name: '站务公告' }
],
activeCategory: 'all',
// 加载状态
loading: false,
// 错误信息
error: null
},
// getter - 从状态派生的计算属性
getters: {
// 判断用户是否已登录
isAuthenticated: state => !!state.token,
// 获取当前用户信息
currentUser: state => state.user,
// 获取帖子列表
allPosts: state => state.posts,
// 获取当前帖子
getCurrentPost: state => state.currentPost,
// 获取分类列表
getCategories: state => state.categories,
// 获取当前激活的分类
getActiveCategory: state => state.activeCategory,
// 获取加载状态
isLoading: state => state.loading,
// 获取错误信息
getError: state => state.error
},
// mutations - 用于修改状态的同步函数
mutations: {
// 设置用户信息
SET_USER(state, user) {
state.user = user
// 持久化存储
localStorage.setItem('user', JSON.stringify(user))
},
// 设置认证令牌
SET_TOKEN(state, token) {
state.token = token
// 持久化存储
localStorage.setItem('token', token)
},
// 清除用户信息(登出)
CLEAR_USER_DATA(state) {
state.user = null
state.token = null
// 清除本地存储
localStorage.removeItem('user')
localStorage.removeItem('token')
},
// 设置帖子列表
SET_POSTS(state, posts) {
state.posts = posts
},
// 设置当前帖子
SET_CURRENT_POST(state, post) {
state.currentPost = post
},
// 添加新帖子到列表
ADD_POST(state, post) {
state.posts.unshift(post) // 添加到列表开头
},
// 更新帖子
UPDATE_POST(state, updatedPost) {
const index = state.posts.findIndex(post => post.id === updatedPost.id)
if (index !== -1) {
state.posts.splice(index, 1, updatedPost)
}
// 如果当前查看的就是这个帖子,也更新currentPost
if (state.currentPost && state.currentPost.id === updatedPost.id) {
state.currentPost = updatedPost
}
},
// 删除帖子
DELETE_POST(state, postId) {
state.posts = state.posts.filter(post => post.id !== postId)
// 如果当前查看的就是这个帖子,清空currentPost
if (state.currentPost && state.currentPost.id === postId) {
state.currentPost = null
}
},
// 设置当前分类
SET_ACTIVE_CATEGORY(state, categoryId) {
state.activeCategory = categoryId
},
// 设置加载状态
SET_LOADING(state, status) {
state.loading = status
},
// 设置错误信息
SET_ERROR(state, error) {
state.error = error
}
},
// actions - 可包含异步操作的函数,用于提交mutation
actions: {
// 用户登录
async login({ commit }, credentials) {
commit('SET_LOADING', true)
commit('SET_ERROR', null)
try {
// 发送登录请求
const response = await axios.post('/api/auth/login', credentials)
const { user, token } = response.data
// 保存用户信息和令牌
commit('SET_USER', user)
commit('SET_TOKEN', token)
// 设置axios默认请求头包含认证令牌
axios.defaults.headers.common['Authorization'] = `Bearer ${token}`
return response
} catch (error) {
commit('SET_ERROR', error.response?.data?.message || '登录失败')
throw error
} finally {
commit('SET_LOADING', false)
}
},
// 用户注册
async register({ commit }, userData) {
commit('SET_LOADING', true)
commit('SET_ERROR', null)
try {
// 发送注册请求
const response = await axios.post('/api/auth/register', userData)
return response
} catch (error) {
commit('SET_ERROR', error.response?.data?.message || '注册失败')
throw error
} finally {
commit('SET_LOADING', false)
}
},
// 用户登出
logout({ commit }) {
// 清除用户数据
commit('CLEAR_USER_DATA')
// 清除axios默认请求头中的认证令牌
delete axios.defaults.headers.common['Authorization']
},
// 获取帖子列表
async fetchPosts({ commit }, { categoryId = 'all', page = 1, size = 10 } = {}) {
commit('SET_LOADING', true)
commit('SET_ERROR', null)
try {
// 构建请求参数
const params = { page, size }
if (categoryId !== 'all') {
params.categoryId = categoryId
}
// 发送获取帖子列表请求
const response = await axios.get('/api/posts', { params })
// 保存帖子列表
commit('SET_POSTS', response.data.content)
return response.data
} catch (error) {
commit('SET_ERROR', error.response?.data?.message || '获取帖子列表失败')
throw error
} finally {
commit('SET_LOADING', false)
}
},
// 获取帖子详情
async fetchPostById({ commit }, postId) {
commit('SET_LOADING', true)
commit('SET_ERROR', null)
try {
// 发送获取帖子详情请求
const response = await axios.get(`/api/posts/${postId}`)
// 保存当前帖子
commit('SET_CURRENT_POST', response.data)
return response.data
} catch (error) {
commit('SET_ERROR', error.response?.data?.message || '获取帖子详情失败')
throw error
} finally {
commit('SET_LOADING', false)
}
},
// 创建新帖子
async createPost({ commit }, postData) {
commit('SET_LOADING', true)
commit('SET_ERROR', null)
try {
// 发送创建帖子请求
const response = await axios.post('/api/posts', postData)
// 添加新帖子到列表
commit('ADD_POST', response.data)
return response.data
} catch (error) {
commit('SET_ERROR', error.response?.data?.message || '创建帖子失败')
throw error
} finally {
commit('SET_LOADING', false)
}
},
// 更新帖子
async updatePost({ commit }, { postId, postData }) {
commit('SET_LOADING', true)
commit('SET_ERROR', null)
try {
// 发送更新帖子请求
const response = await axios.put(`/api/posts/${postId}`, postData)
// 更新帖子
commit('UPDATE_POST', response.data)
return response.data
} catch (error) {
commit('SET_ERROR', error.response?.data?.message || '更新帖子失败')
throw error
} finally {
commit('SET_LOADING', false)
}
},
// 删除帖子
async deletePost({ commit }, postId) {
commit('SET_LOADING', true)
commit('SET_ERROR', null)
try {
// 发送删除帖子请求
await axios.delete(`/api/posts/${postId}`)
// 从列表中删除帖子
commit('DELETE_POST', postId)
return true
} catch (error) {
commit('SET_ERROR', error.response?.data?.message || '删除帖子失败')
throw error
} finally {
commit('SET_LOADING', false)
}
},
// 添加评论
async addComment({ commit }, { postId, content }) {
commit('SET_LOADING', true)
commit('SET_ERROR', null)
try {
// 发送添加评论请求
const response = await axios.post(`/api/posts/${postId}/comments`, { content })
// 如果当前正在查看这个帖子,更新帖子详情
if (this.state.currentPost && this.state.currentPost.id === postId) {
// 获取最新的帖子详情(包含新评论)
await dispatch('fetchPostById', postId)
}
return response.data
} catch (error) {
commit('SET_ERROR', error.response?.data?.message || '添加评论失败')
throw error
} finally {
commit('SET_LOADING', false)
}
},
// 设置当前分类
setActiveCategory({ commit }, categoryId) {
commit('SET_ACTIVE_CATEGORY', categoryId)
}
},
// 模块 - 将状态分割成模块(这里暂时不使用模块)
modules: {
}
})