我正在尝试在Nuxt应用程序中的Vuex商店中设置位置。我已经研究过使用vuexfire,但是,我不确定这在SSR应用程序中是否是最佳选择,或者通常是最简单的最佳实践。
您如何从Firebase Firestore请求并设置状态(在此示例中为“位置”)?
在SSR应用程序中最好使用nuxtServerInit吗?
store / index.js
import Vuex from 'vuex'
import firebase, {auth, db} from '@/services/firebaseinit.js'
const createStore = () => {
return new Vuex.Store({
state: {
user: null,
locations: [],
},
getters: {
// User
activeUser: (state) => {
return state.user
},
// Locations
loadedLocations(state) {
return state.loadedLocations
}
},
mutations: {
// User
setUser (state, payload) {
state.user = payload
},
// Locations
setLocations (state, locations) {
state.locations = locations
}
},
actions: {
// Locations
setLocations(vuexContext, locations) {
vuexContext.commit('setLocations', locations)
},
// Users
autoSignIn ({commit}, payload) {
commit('setUser', payload)
},
signInWithFacebook ({commit}) {
return new Promise((resolve, reject) => {
auth.signInWithPopup(new firebase.auth.FacebookAuthProvider())
resolve()
})
},
signOut ({commit}) {
auth.signOut().then(() => {
commit('setUser', null)
}).catch(error => console.log(error))
},
}
})
}
答案 0 :(得分:1)
我还没有使用vuexfire,但是已经将firebase与nuxt一起使用了,并且效果很好。这就是我所做的。
npm install-保存firebase
创建一个名为firebase.js的文件,并将以下代码放入其中:
import * as firebase from 'firebase'
if (!firebase.apps.length) {
firebase.initializeApp({
apiKey: '<your-api-key>',
authDomain: '<your-domain>',
databaseURL: '<your-url>',
projectId: '<your-id>',
storageBucket: '<your-bucket>'
})
}
export { firebase }
然后您将该文件注册为插件在nuxt.config.js中
plugins: [
'@plugins/firebase.js'
],
您需要在商店的index.js(或您正在使用它的其他文件)顶部导入firebase。
import * as firebase from 'firebase'
然后,您可以根据需要在nuxtServerInit中使用firebase。例如
actions: {
nuxtServerInit({dispatch}, context) {
return Promise.all([
dispatch('get_posts', context),
dispatch('any_other_actions', context)
]);
},
get_posts (vuexContext, context) {
return firebase.database().ref(YOUR DB).once('value')
.then(res => {
//...What you want it to do here
})
},
Firebase功能非常强大,您需要阅读文档以获取有关要执行的功能的详细信息,但是,是的,在nuxt中效果很好。