首页 > 解决方案 > 使用 vuex 确保存储状态中存在变量

问题描述

仅当我有用户详细信息时,我才限制我的应用程序加载到 DOM:

<template>
  <div id="app">
    <template v-if="loggedUser">
    //...
    </template>
  </div>
</template>

loggedUser商店的计算属性在哪里:

 computed: {
    loggedUser() {
      return this.$store.getters.user;
    }
  }

问题是其他组件依赖于现有的这个属性。例如,在一个名为 admin 的组件中/admin,当mounted()我将用户对象从 store 传递给一个方法时,该方法又执行 HTTP 请求:

mounted(){
   this.someFunc(this.$store.getters.user)
}

但问题是有时用户存在,有时用户不存在。如果用户尝试直接从管理页面加载应用程序并且用户不存在,则这是真的。解决此问题的一种可能选择是使用watch从商店返回用户的计算属性:

computed: {
    user() {
        return this.$store.getters.user;
       }
    },
watch: {
    user(newVal) {
        if(newVal) this.someFunc(this.$store.getters.user)
      }
    }

虽然这可能有效,但即使对于这个例子来说也感觉很乏味。然而,由于这个问题,出现了更大更复杂的问题。另一个可能的选择是尝试将用户保存在 localStorage 中,但我猜 vuex 应该能够在不使用任何类型的客户端存储解决方案的情况下解决我的问题。知道如何解决这个问题吗?是否有更强大的方法来确保用户在我的整个应用程序中都可用?

标签: vue.jsvuex

解决方案


如果您使用 vue 路由器,您可以在那里对用户进行身份验证:

const ifAuthenticated = (to, from, next) => {
if (store.state.token) {  // or state.user etc.
  next()
  return
}
next('/Adminlogin')  // if not authenticated

路由器路径如下所示:

{
  path: '/AdminUI',
  name: 'AdminUI',
  component: AdminUI,
  beforeEnter: ifAuthenticated

}

另一种可能的解决方案:

<v-template
    v-show="$store.state.isUserLoggedIn"
</v-template>

不要忘记import { mapState } from "vuex";

并在store

getters: {
  isUserLoggedIn: state => !!state.token
}

推荐阅读