【问题标题】:Vuejs redirect on enterVuejs在输入时重定向
【发布时间】:2018-04-22 17:20:48
【问题描述】:

如果有人在未登录的情况下尝试进入我的应用程序,我该如何重定向?

我在我的 App.vue 中使用此代码

export default {
  name: 'App',
  created() {
    this.$router.beforeEach((to, from, next) => {
      if (this.$store.getters.isLogado) {
        next();
      } else {
        console.log('Stop');
        debugger;
      }
    });
  },
};

但是如果我的用户输入 http://myapp/users 应用程序输入 /users 然后如果他尝试导航 vue 输入 beforeEach

【问题讨论】:

    标签: vue.js vue-router


    【解决方案1】:

    我将向您展示我如何在我的应用程序中使用身份验证保护。

    auth.js

    import { store } from "../../store/store";
    
    export default function (Vue) {
      Vue.auth = {
        isAuthenticated () {
          return store.getters.isLogged
        },
      }
    
      Object.defineProperties(Vue.prototype, {
        $auth: {
          get () {
            return Vue.auth
          }
        }
      })
    
    }
    

    ma​​in.js

    import Vue from 'vue'
    import App from './App.vue'
    import router from './router'
    import { store } from '../store/store'
    import Auth from './services/Auth'
    
    Vue.use(Auth)
    
    router.beforeEach((to, from, next) => {
      if (to.name === 'Login') { //if user goes to login page
        if (Vue.auth.isAuthenticated()) { //if is authenticated
          next({name: 'notFound'})
        }else {
          next()
        }
      }else if (to.name === 'notFound') { //if user tries to go to notFound
          next()
      }else { //if user tries any other url
        if (Vue.auth.isAuthenticated()) {
          next()
        } else {
          next({name: 'notFound'})
        }
      }
    
    })
    
    
    /* eslint-disable no-new */
    new Vue({
      el: '#app',
      router,
      store,
      template: '<App/>',
      components: { App }
    })
    

    这是一个很好的做法。如果你不理解它并且它对你没有帮助,那么回答你关于你发布的代码的问题如下:

    import store from './store'
    
    export default {
      name: 'App',
      beforeRouteEnter(to, from, next){
        if (store.getters.isLogado) {
          next()
        }else {
          next({name: 'YouRouteName_you_want_to_navigate'})
        }
      },
    };
    

    或者:

    export default {
      name: 'App',
      created() {
       if(this.$store.getters.isLogado){
          next()
       }else{
        this.$router.push('ThePathYouWant')
       }
      }
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-05-09
      • 1970-01-01
      • 2019-09-12
      • 1970-01-01
      • 2021-12-24
      • 1970-01-01
      • 1970-01-01
      • 2014-09-07
      相关资源
      最近更新 更多