如何在Vue中监视多个商店值?

时间:2019-06-09 14:29:52

标签: vue.js vuex vue-router

在我们的项目中,有一种情况是根据 路由参数 获取 用户个人资料

在登录和刷新时,当前用户详细信息将保存在商店中。

当用户 点击 他的个人资料页面时,路线参数会更改为其唯一ID。

根据该ID提取 用户详细信息

应用程序中添加了多个角色,其中Admin可以访问所有个人资料,而普通用户只能查看其个人资料。

我们需要检查用户是否有权访问其他配置文件数据,因为这需要两个详细信息。 1.当前用户的唯一ID,具有角色 2.路径参数中的配置文件ID。

因此,为了检查用户是否具有角色,我们需要 监视 以获取 两个值 路由 参数 用户 详细信息。

我们如何在Vue和Vuex中使用手表?

下面的代码说明了这种情况!

 // Current user details fetched on refresh and logging in.
 @Getter private currentUser!: User;


 @Watch('$route.params.id', { immediate: true })
  private refreshProfile(newVal: any, oldVal: any) {
    this.employeeId = this.$route.params.id;
    if (this.employeeId) {
      const hasPrivilege = this.$can(this.$permissions.CREATE, this.$modules.EMPLOYEE);
      const isUserProfile = this.currentUser.employeeCompanyId == this.employeeId;
      debugger;
      if (!hasPrivilege && !isUserProfile) {
        this.logout();
      } else {
        this.getUser({ employeeId: this.employeeId });
      }
    }
  }

以上代码无需刷新即可完美运行。当用户尝试手动输入以直接在URL中查看其个人资料或其他个人资料时,无论有没有许可,它都将注销,因为当前用户详细信息是异步获取的!

任何想法都可能有帮助!!

预先感谢您的耐心和理解。

0 个答案:

没有答案