如何在Vue的store中存储当前登录用户的ID
Vue store模块无法使用
this.$store的解决方案 根本原因
this.$store是Vue为组件实例专门注入的全局属性,仅在Vue组件的运行上下文中生效。store文件本身是独立的JS模块,没有绑定Vue组件实例,自然不存在该属性。- store内部操作自身状态不需要依赖
this.$store,Vuex内置的上下文参数已经满足所有操作需求。
实现方案
你补充的代码已经是正确实现,核心逻辑如下:
- actions的第一个入参就是当前store的上下文对象,可直接通过它调用
commit触发mutation、调用dispatch触发其他action,也可直接访问state和getters属性 - 登录接口请求完成后,直接通过上下文对象执行
commit,将返回的userId存入state即可。
export default createStore({ state: { user: null, userId: null }, mutations: { setUser(state, user) { state.user = user; console.log("User set in store"); }, setUserId(state, userId) { state.userId = userId; console.log("User ID set in store"); } }, getters: { getUser: state => { console.log('Retrieving user...') return state.user; } }, actions: { async login(store, credentials) { let response = await(await fetch("http://localhost:4000/api/login", { method: "POST", body: JSON.stringify(credentials), credentials: "include", })).json(); store.commit('setUserId', response.userId); }, }, });
补充注意点
- 如果需要在其他普通JS文件中访问store实例,可直接引入store模块的导出实例使用,无需依赖
this.$store - 如果是Pinia的store,逻辑同理,可通过
this访问当前store实例的属性和方法,不需要额外调用全局store。
内容的提问来源于stack exchange,提问作者noumenal
相关产品推荐
相关产品推荐

