【问题标题】:Vue Router Guard Method still allowing page loadVue Router Guard Method 仍然允许页面加载
【发布时间】:2020-08-08 02:42:16
【问题描述】:

我正在使用以下保护 const 来防止用户在他们没有保存在 cookie 上的令牌时进入页面。但是,如果我尝试足够的时间,用户能够进入页面但组件不加载,这只是一个空白页面

我还应该在我的路由器文件中添加什么来防止这种事情发生?

这是我的守卫常数:

const guard = function(to, from, next) {
  const token = Cookies.get('token')
  if(typeof token === 'undefined' || token === null ){
    this.$store.dispatch('logout')
    window.location.href = "/";
  } else {
    next();
  }
};

【问题讨论】:

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


    【解决方案1】:

    尝试使用next('/') 而不是window.location.href = "/"

    import store from 'path/to/store/
    const guard = function(to, from, next) {
      const token = Cookies.get('token')
      if(typeof token === 'undefined' || token === null ){
       store.dispatch('logout');
        next('/');
      } else {
        next();
      }
    };
    

    【讨论】:

    • 它也给了我以下错误:Cannot read property '$store' of undefined 但是我在 main.js 中声明了我的商店
    • 像在 main.js import store from 'path/to/store/ 中一样将其导入到路由器文件中
    猜你喜欢
    • 1970-01-01
    • 2013-03-14
    • 2021-04-20
    • 1970-01-01
    • 1970-01-01
    • 2013-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多