首页 > 解决方案 > 如何将用户状态设置为空?

问题描述

我在 Nuxt 和 Typescript 中使用 VueX。我想让我的用户的初始状态为空。设置state.authenticatedUser:null工作正常。但是一旦我尝试为它分配一个 IAuthenticatedUser ,它就不会知道类型,因为我分配了 null 并且它会在我放置评论的地方引发错误。

那么我怎样才能让我的 authenticatedUser 最初为 null 呢?

import { getAccessorType, mutationTree, actionTree } from 'nuxt-typed-vuex';

import IAuthenticatedUser from '~/ts/interfaces/firebase/user/authenticated_user.ts';
import * as counter from './counter';

type RootState = ReturnType<typeof state>

export const state = () => ({
    authenticatedUser: {} as IAuthenticatedUser, //I want this to be null
})

export const getters = {

}

export const mutations = mutationTree(state, {
    setAuthenticatedUser(state, newValue: IAuthenticatedUser) {
        state.authenticatedUser = newValue // If state.authenticateUser == null I cannot asign newValue becuase state.authenticateUser has a type of null
    },
    logOut(){
        state.authenticatedUser = null; // I cannot do this since it not of type IAuthenticatedUser
    }
})

export const actions = actionTree(
    { state, getters, mutations },
    {
        async onAuthenticationStateChangedAction({ commit, dispatch }, { authUser, claims }) {

            if (!authUser) {
                commit('logOut');
                return
            }

            const { uid, email, emailVerified, displayName, photoURL } = authUser

            commit('setAuthenticatedUser', {
                uid,
                email,
                emailVerified,
                displayName,
                photoURL,
            })
        }
    }
)

export const accessorType = getAccessorType({
    actions,
    getters,
    mutations,
    state,
    modules: {
        counter,
    },
})

标签: typescriptvue.jsvuexnuxt.js

解决方案


为将其初始化为 null 并声明为该类的状态定义一个类state应该可以工作

export class RootState {
    authenticatedUser: (IAuthenticatedUser | null) = null
}

export const state: RootState = {} as RootState;

authenticatedUser然后将null直到你分配给它

state.authenticatedUser = {} as IAuthenticatedUser

由于该类型被声明为允许为 null,因此您以后也应该能够再次分配 null。

state.authenticatedUser = null

推荐阅读