我试图根据用户是否是零售商来呈现不同的UI。我认为大多数情况都正确,但是在应用初始化时,我想检查用户是否为零售商(这将调度checkAuth动作)。

我尝试运行以下命令以从Firebase获取isRetailer属性的值。

firebase.database().ref('/users/' + user.uid + '/isRetailer').once('value').then(snapshot => snapshot.val()


然后我根据结果调度一些动作。由于某些原因,即使用户的isRetailer属性为true,我的Vuex状态的isRetailer部分也不会从false更新。

我不确定为什么,但是我猜测它与我的firebase参考有关。我的完整代码如下。谢谢!

import firebase from 'firebase'

const authentication = {
    state: {
        isAuthed: false,
        authId: '',
        isRetailer: false
    },
    mutations: {
        authUser (state, user) {
            state.isAuthed = true;
            state.authId = user.uid;
        },
        notAuthed (state) {
            state.isAuthed = false;
            state.authId = '';
            state.isRetailer = false
        },
        isRetailer (state) {
            state.isRetailer = true
        },
        isNotRetailer (state) {
            state.isRetailer = false
        }
    },
    actions: {
        checkUser (context, user) {

            if (!user.uid) {

                // Do nothing.

            } else if (firebase.database().ref('/users/' + user.uid + '/isRetailer').once('value').then(snapshot => snapshot.val()) === true) {

                context.commit('authUser', user);

                context.commit('isRetailer');

            } else {

                context.commit('authUser', user);

                context.commit('isNotRetailer');
            };
        },
        signOut (context) {
            context.commit('notAuthed')
        },
        setRetailer (context, payload) {

            // Set retailer info in Firebase.

            var uid = payload.user.uid;
            firebase.database().ref('/users/' + uid).set({
                name: payload.name,
                email: payload.email,
                location: payload.retailerLocation,
                isRetailer: payload.isRetailer
            });

        },
        setNewUser (context, payload) {

            // Sets a user in firebase w/ a isRetailer value of false.

            var uid = payload.user.uid;

            firebase.database().ref('/users/' + uid).set({
                name: payload.name,
                email: payload.email,
                isRetailer: payload.isRetailer
            });
        }
    },
    getters: {}
};

export default authentication;

最佳答案

发生这种情况的原因可能是您为突变和状态变量指定了相同的名称:isRetailer,我现在没有任何引用,但是可能不会触发突变。您可以通过设置突变来尝试一次不同的名称,例如:

mutations: {
    ...
    ...
    setIsRetailer (state) {
        state.isRetailer = true
    },
    isNotRetailer (state) {
        state.isRetailer = false
    }
},


并在行动中使用它:

actions: {
    checkUser (context, user) {
        ...
        ...

            context.commit('authUser', user);
            context.commit('setIsRetailer');

        }

09-20 03:55