VueX中 state属性更改但是 视图不同步更新的问题

新手上路,请多包涵

我希望通过一个属性isLogin来控制在组件A中是否显示两个小组件

isLogin属性存在于一个cugber.js的子模块当中

我在组件A中存在如下代码:

<a-menu-item key="login" v-if="!isLogin" @click="loginRedirect">
  <span>
  <a-icon type="login"/>
    Sign in
  </span>
</a-menu-item>
<a-menu-item key="registry" v-if="!isLogin" @click="registryRedirect">
  <span>
    <a-icon type="user-add"/>
    Sign up
  </span>
</a-menu-item>

//无关代码省略

//引入isLogin属性

computed: {
  ...mapState({
    isLogin:state => state.cugber.isLogin,
    cugber:state => state.cugber.user
 })
},

cugber.js模块中actions代码为


async login({commit,state}, accountInfo) {
    console.log(accountInfo)
    const data = await CugberOperation('login', { //向后台发送请求,验证用户的名称和密码
        studentNum: accountInfo.studentNum,
        password: accountInfo.password
 })
    console.log(data)
    let validateRes = {
        errorCode: true,
        enable: false
 } // 向外返回后台的判断结果,用以处理界面的动效
    if (!validator.errorCode(data.code)) {
        validateRes.errorCode = false
        if (data.resultJSON.enable) {
            localStorage.setItem('user', data.user)
            commit('changeLoginStatus', true) // 通过commit的方式更改isLogin的值
            console.log(state.isLogin)
            commit('getUser', data)
            validateRes.enable = true
 }
    }
    return validateRes //向外返回判断结果
}

我在另一个组件B中通过actions的方式对isLogin属性进行了更改:

代码如下:

let validateRes =  await this.$store.dispatch('login', {
  studentNum: this.ruleForm.account,
  password: this.ruleForm.pass
})

通过很多位置的测试,我确定isLogin的值发生了改变,但是组件A的视图没有发生对应的更改。

我查看了很多帖子,没有找到问题所在。

希望大神指点。

如果有什么不明确的地方,请联系我补充。

谢谢。

阅读 2.2k
1 个回答

你试试使用 getter 来获取 cugber.isLogincugber.user 试试,而不是用 mapState
感觉是因为对象深度的问题。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题