【问题标题】:Vue redirect after getting store's values获取商店值后的Vue重定向
【发布时间】:2021-11-26 01:15:50
【问题描述】:

我试图创建一个编辑页面 /edit/:id,其中输入的值来自 vuex 存储,但如果存储没有具有相同参数 id 的任务,我想要重定向到 /404,我该如何实现呢?尝试了 created() 但它没有用。我正在使用 Vue3

<script>
export default {
  name: "EditTaskForm",
  data() {
    return {
      newTaskDesc: "",
    };
  },
  created() {
    const task = this.$store.getters.getTaskById(Number(this.$route.params.id));
    if (!task) this.$router.push("/404");
  },
  mounted() {
    const task = this.$store.getters.getTaskById(Number(this.$route.params.id));
    this.newTaskDesc = task.desc;
  },
  methods: {
    submitEdit() {
      this.$store.dispatch("editTask", {
        newTaskDesc: this.newTaskDesc,
        id: Number(this.$route.params.id),
      });
      this.$router.push("/");
    },
  },
};
</script>

【问题讨论】:

  • 这就是路由守卫的用途。

标签: vue.js vuex vue-router vuejs3


【解决方案1】:

尝试以下操作:

beforeRouteEnter(to, from, next) {
  const task = this.$store.getters.getTaskById(Number(this.$route.params.id));
  if (!task) this.$router.push("/404");
},
<script>
export default {
  name: "EditTaskForm",
  data() { ... },
  mounted() { ... },
  methods: { ... },
  beforeRouteEnter(to, from, next) {
    const task = this.$store.getters.getTaskById(Number(this.$route.params.id));
    if (!task) this.$router.push("/404");
  }
};
</script>

Navigation Guards

【讨论】:

    猜你喜欢
    • 2015-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-30
    • 2021-04-08
    • 2020-08-18
    相关资源
    最近更新 更多