确保变量使用vuex在商店的状态存在

问题描述 投票:0回答:1

我限制我的应用程序只,如果我有用户的详细信息加载到DOM:

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

其中loggedUser是从存储一个计算属性:

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

问题是,其他组件依赖于该物业现有的。在一个组件中,被称为路线/admin例如,下管理员当mounted()我通过用户对象从商店,后者又执行的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.js vuex
1个回答
0
投票

如果您使用路由器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
  }
© www.soinside.com 2019 - 2024. All rights reserved.