【问题标题】:Firebase fetch on Nuxtjs before rendering渲染前在 Nuxtjs 上获取 Firebase
【发布时间】:2018-11-02 15:25:02
【问题描述】:

我有一个 vuejs + firebase 项目。

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

src/存储

├───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 返回未定义,我认为那是因为我必须在渲染之前获取数据。 我也加了

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

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

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

说实话,我不懂 nuxtjs,需要帮助才能像非 nuxtjs 项目一样轻松获取数据。

【问题讨论】:

    标签: javascript firebase firebase-realtime-database vue.js nuxt.js


    【解决方案1】:

    据我了解,您的问题主要涉及如何在 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

    【讨论】:

      猜你喜欢
      • 2018-12-24
      • 1970-01-01
      • 2020-08-16
      • 1970-01-01
      • 1970-01-01
      • 2021-06-04
      • 1970-01-01
      • 1970-01-01
      • 2019-12-31
      相关资源
      最近更新 更多