【问题标题】:Nuxt / Vue redirect if vuex property is undefind not working如果 vuex 属性未定义,则 Nuxt / Vue 重定向不起作用
【发布时间】:2021-03-20 15:51:52
【问题描述】:

我运行了一个 nuxt 应用程序,它有一个帐户页面。此帐户页面使用用户的 mapState 计算属性。用户数据通过 props 用于帐户页面模板及其子组件中。

每当我通过转到 myurl/account 启动应用程序时,我都会收到“无法读取未定义的属性 x”。这对我来说很明显,因为当我立即转到 /account 时没有登录用户。

我试图将路由推回到帐户页面的 created() 挂钩中的 /login 页面,但它不起作用。我仍然遇到同样的错误。

如何处理在模板使用的属性设置之前尝试访问页面的用户?创建的钩子仅记录服务器端,而不是 chrome 的开发工具。 this.$router.push("login") 不应该工作吗?

帐户页面

<template>
  <v-container fluid class="px-0 py-0 mt-12">
    <v-row>
      <accountheader :user="user" :company="company" />
    </v-row>
  </v-container>
</template>

<script>
import { mapState } from "vuex";

export default {
  transitions: "page",
  computed: {
    ...mapState("user", {
      company: (state) => state.company,
      user: (state) => state.user,
    }),
  },
  head: {
    title: "ACCOUNT",
    meta: [
      {
        hid: "description",
        name: "description",
        content: "account page",
      },
    ],
  },
  created() {
    if (this.user === undefined) {
      this.$router.push("/login");
    }
  },
};
</script>

<style></style>

【问题讨论】:

    标签: vue.js nuxt.js vuex router


    【解决方案1】:

    我自己设法通过在页面文件本身中实现一个中间件来解决这个问题。万一有人遇到同样的问题。

    解决方案

    middleware({ store, redirect }) { // If the user is not authenticated if (store.state.user.user === undefined) { return redirect("/login"); } },

    【讨论】:

      猜你喜欢
      • 2020-01-11
      • 2021-04-29
      • 1970-01-01
      • 2020-08-25
      • 2021-05-31
      • 1970-01-01
      • 2020-08-08
      • 1970-01-01
      • 2020-08-11
      相关资源
      最近更新 更多