【问题标题】:Vue.js - control the router from inside a mutation in Vuex StoreVue.js - 从 Vuex Store 的突变内部控制路由器
【发布时间】:2020-12-11 17:44:32
【问题描述】:

我有以下问题:

这是我的突变之一:

tryAutoLogin(state) {
  console.log("Trying auto login...");
  const token = window.localStorage.getItem("token");
  if (!token) {
    return;
  }
  const expirationDate = window.localStorage.getItem("token_exp");
  const now = new Date();
  if (now >= expirationDate) {
    return;
  }
  state.userData.loggedIn = true;
  state.userData.username = token.identity;
  // desired: this.$router.push("/dashboard") => results in undefined
}

目前我在组件的创建阶段在组件内提交了这个突变:

  created() {
    this.$store.commit("tryAutoLogin");
    this.$router.push("/dashboard");
  }

这不是一个好方法,因为我必须输出一个值,将它存储在一个变量中,然后使用 if/else 来处理这个this.$router.push("/dashboard")

我怎样才能优雅地解决这个问题?在 // desired 评论中的突变内部是有利的。有没有办法访问Vuex商店里面的路由器?

【问题讨论】:

  • 尝试使用vue-router guards
  • 我想说在突变中做你想做的事情不是一个好习惯,你可以使用导航守卫。

标签: vue.js vuejs2 vue-component vuex vue-router


【解决方案1】:

将 vue 组件实例传递给突变,如:

 this.$store.commit("tryAutoLogin",this);
 

在突变中将其添加为参数vm,然后将其用作vm.$router.push("/dashboard")

tryAutoLogin(state,vm) {
  console.log("Trying auto login...");
  const token = window.localStorage.getItem("token");
  if (!token) {
    return;
  }
  const expirationDate = window.localStorage.getItem("token_exp");
  const now = new Date();
  if (now >= expirationDate) {
    return;
  }
  state.userData.loggedIn = true;
  state.userData.username = token.identity;
  vm.$router.push("/dashboard") 
}

【讨论】:

  • 你应该像中间件一样使用vue-routerguards来加入一些路由,在那里你可以应用相应的逻辑。同样在您的组件内部,您可以使用 beforeRouteEnter 保护作为次要选项
猜你喜欢
  • 2019-05-19
  • 2021-02-19
  • 2018-08-10
  • 2017-11-02
  • 2019-01-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-28
相关资源
最近更新 更多