我正在使用Vue.js和Firebase开发应用程序 .
我已经设法使用电子邮件/密码使登录工作,并且可以在state.currentUser下的Vue.js状态下成功存储firebase.auth()用户信息 .
但是,根据Firebase指南,我有更多信息存储在'/ users'参考号下 . 例如 . /用户/ UID
我也想把这些数据拉到vuex商店(state.userMeta),所以我可以在网站上使用它,但是在刷新后它永远不会工作 . 如果我不刷新,注销然后重新登录,它会填充状态 .
任何帮助都将受到大力赞赏!
詹姆士
auth.js
import { auth, db } from '@/config/database'
import store from '@/vuex/store'
const init = function init () {
auth.onAuthStateChanged((user) => {
if (user) {
store.dispatch('setUser', user)
} else {
// User is signed out.
store.dispatch('setUser', null)
}
}, (error) => {
console.log(error)
})
}
export { init }
store.js
import Vue from 'vue'
import Vuex from 'vuex'
import createPersistedState from 'vuex-persistedstate'
import { db } from '@/config/database'
Vue.use(Vuex)
const state = {
currentUser: null,
userMeta: null
}
const mutations = {
SET_USER (state, user) {
if (user) {
state.currentUser = user
db.ref('users/' + user.uid).on('value', function (s) {
state.userMeta = s.val()
})
} else {
state.currentUser = null
state.userMeta = null
}
}
}
const actions = {
setUser ({commit}, user) {
commit('SET_USER', user)
}
}
const getters = {
currentUser: state => state.currentUser
}
export default new Vuex.Store({
state,
mutations,
actions,
getters,
plugins: [createPersistedState()]
})
App.vue
<template>
<div id="app">
<router-view></router-view>
</div>
</template>
<script>
import * as auth from '@/config/auth'
const initApp = function initApp () {
auth.init()
}
export default {
name: 'app',
created: initApp
}
</script>
<style lang="scss" src="./assets/sass/style.scss"></style>
main.js
// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import VueFire from 'vuefire'
import router from './router'
Vue.config.productionTip = false
Vue.use(VueFire)
import store from '@/vuex/store'
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
store,
template: '<App/>',
components: { App }
})
1 回答
页面刷新时清除Vuex状态 .
我用这种方法对它进行了排序
In main.js
因此,当刷新时,您的状态将自动同步 .
In your components
刷新后,尝试使用
this.$firebase.auth().currentUser
并不起作用 - 但通过Auth更改再次设置状态似乎可以解决问题