渲染前在 Nuxtjs 上获取 Firebase

Firebase fetch on Nuxtjs before rendering

我有一个 vuejs + firebase 项目。

我有三个 vuex 存储模块,它们是 back, common, front 我的商店文件夹结构是这样的:

src/store

├───back
│   └───index.js
├───common
│   └───index.js
├───front
│   └───index.js

没有 nuxtjs 我可以像这样获取用户通知

    fetchUserNotifications({commit, getters}) {
        let getUser = store.getters["common/getUser"];
        return firebase
            .database()
            .ref("users/" + getUser.id)
            .child("notifications")
            .limitToLast(5)
            .on("value", snapshot => {
                commit("setUserNotifications", snapshot.val());
            });
    },

但是 nuxt js getUser returns 未定义,我认为那是因为我必须在渲染之前获取数据。 我还添加了

setTimeout(() => console.log(store.state.front.user), 5000);

但每次结果都是空的。 当我检查 Chrome 上的 Vuejs 开发人员工具时,一切看起来都很好,我的数据就在那里。

我搜索了文档并找到了 nuxtServerInit() 但不知道如何使用它。

老实说,我无法理解 nuxtjs,需要帮助才能像非 nuxtjs 项目一样轻松获取数据。

据我了解,您的问题主要涉及如何在 NuxtJS 中设置商店模块。这是一个快速示例,说明我如何根据您目前分享的有关设置和获取用户以及处理根存储操作中的 nuxtServerInit 函数的内容来设置您的根存储模块:

// store/index.js

export const state = () => ({
  user: null,
  userNotifications: null
})

export const mutations = {
  setUser(state, userData) {
    state.user = userData
  },

  setUserNotifications(state, userNotifications) {
    state.userNotifications = userNotifications
  }
}

export const getters = {
  getUser (state) {
    return state.user
  }
}

export const actions = {
  nuxtServerInit ({ commit }) {
    return httpClient.get('/url/to/get/user/data')
      .then(({ data }) => {
        commit('setUser', data)
      })
  }
}


// where you fetch notifications in a component or page
fetchUserNotifications({commit, getters}) {
  let user = this.$store.getters.getUser();
  return firebase
    .database()
    .ref('users/' + user.id)
    .child('notifications')
    .limitToLast(5)
    .on('value', snapshot => {
      commit('setUserNotifications', snapshot.val());
    });
},
...

如果您有任何疑问,请参阅 NuxtJS 文档中关于 Vuex 存储的模块模式:https://nuxtjs.org/guide/vuex-store