Vue 之导航守卫

导航守卫可以看做是 vue-router 的生命周期钩子

如果用户未登陆就前往发帖页面,如何用户重定向到登陆页面?

思路
使用 beforeEach 在页面跳转前对用户的登陆状态进行检查

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title></title>
    <script src="https://unpkg.com/vue/dist/vue.js"></script>
    <script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>
  </head>
  <body>
    <div id="app">
      <h1>Hello App!</h1>
      <p>
        <router-link to="/login">Go to login</router-link>
        <router-link to="/post">Go to post</router-link>
      </p>

      <router-view></router-view>
    </div>
  </body>
  <script>
    const login = { template: '<div>login</div>' }
    const post = { template: '<div>post</div>' }

    const routes = [
      { path: '/login', component: login },
      { path: '/post', component: post }
    ]

    const router = new VueRouter({
      routes: routes
    })

    router.beforeEach(function (to, from, next) {
      let login = false

      if (!login && to.path == '/post') {
        next('/login')
      } else {
        next()
      }
    })

    const app = new Vue({
      router
    }).$mount('#app')
  </script>
</html>

相关推荐