如何将当前用户 ID 存储在 Vue 商店中?

How can I store the current user id in the Vue store?

我希望在登录时保存 UserId,但是,我无法使用 this.$store 从商店本身访问商店,大概是因为它不是 Vue 组件而是 JS 文件。

编辑:基于下面代码中的答案的解决方案


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);
    },
  },
});```

您的操作可以通过参数 async login(store, credentials)

访问商店引用

因此,当您收到响应时,您可以从商店参考中调用变更setUserId

.then(function (response) {
    store.commit('setUserId', response.json().id);
  })