首页 文章

Vue路由器导航从组件内部获取

提问于
浏览
0

我在我的vuex store.js中使用来自集中状态管理的vuex我将登录状态存储为布尔值,如下所示

export const store = new Vuex.Store({
state: {
loggedIn: false,
userName: 'Guest',
error: {
    is: false,
    errorMessage: ''
}
},
getters: {
g_loginStatus: state => {
    return state.loggedIn;
},
g_userName: state => {
    return state.userName;
},
g_error: state => {
    return state.error;
}
}
)};

当用户登录时我将loginstatus设置为true并删除登录按钮并将其替换为注销按钮一切正常但问题是当用户登录时如果我直接在搜索栏中输入登录组件的路径我能够再次导航到登录页面我想要预防此行为如果登录使用并在搜索栏中搜索登录页面的路径,则必须将其重定向到主页

我已尝试在登录组件中使用 beforeRouteEnter 但我们没有访问 this 实例,因为组件尚未加载所以我如何从我的商店检查登录状态

我在login.vue中的脚本

script>

export default{
    data(){
        return{
            email: '',
            password: ''
        };
    },
    methods: {
        loginUser(){
            this.$store.dispatch('a_logInUser', {e: this.email, p: this.password}).then(() =>{
                this.$router.replace('/statuses');

            });
        }
    },
    beforeRouteEnter (to, from, next) {
        next(vm => {
            if(vm.$store.getters.g_loginStatus === true){
                 //what shall i do here
            }
        })
    }
}

2 回答

  • 0

    您可以将用户重定向到主页或其他相关页面:

    mounted () {
            if(vm.$store.getters.g_loginStatus === true){
                 this.$router('/')
            }
    }
    beforeRouteEnter (to, from, next) {
        next(vm => {
            if(vm.$store.getters.g_loginStatus === true){
                 next('/')
            }
        })
    }
    

    来自docs

    next:Function:必须调用此函数来解析钩子 . 该操作取决于提供给next的参数:next():移动到管道中的下一个钩子 . 如果没有留下挂钩,则确认导航 . next(false):中止当前导航 . 如果浏览器URL已更改(由用户手动或通过后退按钮),则会将其重置为来自路由的URL . next('/')或next({path:'/'}):重定向到其他位置 . 当前导航将中止,并将启动一个新导航 .

  • 0

    将导航警卫放在不在页面/组件中的路径中并在路由文件上调用状态getter要好得多 .

    // /router/index.js
    
    import Vue from 'vue'
    import Router from 'vue-router'
    import store from '../store'
    
    // Protected Pages
    import Dashboard from '@/views/dashboard'
    
    // Public Pages
    import Dashboard from '@/views/login'
    
    Vue.use(Router)
    
    // If you are not logged-in you will be redirected to login page
    const ifNotAuthenticated = (to, from, next) => {
      if (!store.getters.loggedIn) {
        next()
        return
      }
      next('/') // home or dashboard
    }
    
    // If you are logged-in/authenticated you will be redirected to home/dashboard page    
    const ifAuthenticated = (to, from, next) => {
      if (store.getters.loggedIn) {
        next()
        return
      }
      next('/login')
    }
    
    const router = new Router({
      mode: 'history',
      linkActiveClass: 'open active',
      scrollBehavior: () => ({ y: 0 }),
      routes: [
        {
          path: '/',
          redirect: '/dashboard',
          name: 'Home',
          component: Full,
          children: [
            {
              path: 'dashboard',
              name: 'Dashboard',
              component: Dashboard,
              beforeEnter: ifAuthenticated
            },
          ]
        },
        {
          path: '/login',
          name: 'Login',
          component: Login,
          beforeEnter: ifNotAuthenticated
        },
        {
          path: '*',
          name: 'NotFound',
          component: NotFound
        }
      ]
    })
    
    export default router
    

    您还可以使用vue-router-sync软件包获取商店值的值

相关问题