我有一个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
返回undefined,我认为这是因为我必须在渲染之前获取数据。
我还添加了
setTimeout(() => console.log(store.state.front.user), 5000);
但每次结果都为null。 当我在Chrome上查看Vuejs开发人员工具时,一切看起来都很好,我的数据就在那里。
我搜索了文档并找到了nuxtServerInit()
,但无法弄清楚如何使用它。
说实话,我无法理解nuxtjs,并且需要帮助来获取数据,就像非nuxtjs项目一样。
答案 0 :(得分:1)
据我了解,您的问题主要涉及如何在NuxtJS中设置存储模块。这是一个快速的示例,该示例说明了如何根据您到目前为止在设置和获取用户以及处理root存储操作中的nuxtServerInit
函数方面共享的内容来设置root存储模块:
// 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());
});
},
...
如果有任何疑问,请参阅带有Vuex存储的模块模式下的NuxtJS文档:https://nuxtjs.org/guide/vuex-store