程序问答   发布时间:2022-06-01  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了用户未登录时重定向 Vue Router大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

如何解决用户未登录时重定向 Vue Router?

开发过程中遇到用户未登录时重定向 Vue Router的问题如何解决?下面主要结合日常开发的经验,给出你关于用户未登录时重定向 Vue Router的解决方法建议,希望对你解决用户未登录时重定向 Vue Router有所启发或帮助;

我在 Vue Js 中的路由器有问题。我正在尝试定义需要身份验证的页面。如果用户未登录,我使用 router.beforeach 来重定向用户。 然而,问题是当我尝试登录用户时,因为它不会将用户重定向到主页,即使它已登录(用户对象有一个令牌)在本地存储中)。

登录:

                    if(this.$store.dispatch('loginUser',user)){
                      this.$router.push('/dashboard')
                    }

                  //.then(() => {Console.log("sono nel then"); this.$router.push('/dashboard')})
                  //.catch(err => console.log(err));

@H_933_5@ma​​in.Js:

import Vue from "vue";
import App from "./App.vue";
import router from "./router";
import store from "./store";
import vuetify from "./plugins/vuetify";
import Axios from 'axios'

Vue.config.productionTip = false;

router.beforeEach((to,from,next)=>{
  if(to.matched.some(record => record.Meta.requiresAuth)){
    console.log("sono nel router");
    if(localstorage.getItem('token') !== null){
      next();
      return;
    }
    next('/');
  }
    else{
      next();
    }
})

new Vue({
  router,store,vuetify,render: h => h(App)
}).$mount("#app");

Vue.prototype.$http = Axios;
const token = localstorage.getItem('token')
if (token) {
  Vue.prototype.$http.defaults.headers.common['Authorization'] = token
}

router.Js


Any suggestion to how to solve this problem?
import Vue from "vue";
import VueRouter from "vue-router";
import Dashboard from "../vIEws/Dashboard.vue";
import HomeLogin from "../vIEws/HomeLogin.vue"
import About from "../vIEws/About.vue";

Vue.use(VueRouter);

const routes = [
  {
    path: "/",name: "HomeLogin",component: HomeLogin
  },{
    path: "/dashboard",name: "dashboard",component: Dashboard,Meta:{
      requiresAuth: true,}
  },{
    path: "/about",name: "About",component: About,Meta:{
      requiresAuth: true
    }
  },];

const router = new VueRouter({
  routes
});


export default router;

编辑:我想我理解了这个问题。如果我尝试运行此代码:

                      this.$store.dispatch('loginUser',user)
                      .then(() => {this.$router.push('/dashboard')})
                      .catch(err => console.log(err));

它没有进入 then 子句。有谁知道为什么?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

大佬总结

以上是大佬教程为你收集整理的用户未登录时重定向 Vue Router全部内容,希望文章能够帮你解决用户未登录时重定向 Vue Router所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签: