简单笔记 VueRouter

2020-07-22  本文已影响0人  谢玉胜

核心原理:

将组件 (components) 映射到路由 (routes),然后告诉 Vue Router 在哪里渲染它们

  1. 定义两个组件
const Foo = { template: '<div>foo</div>' }
const Bar = { template: '<div>bar</div>' }
  1. 形成路由映射
const routes = [
  { path: '/foo', component: Foo },
  { path: '/bar', component: Bar }
]
  1. .建立路由
const router = new VueRouter({
   routes: routes
})
  1. 将路由绑定到视图
const app = new Vue({
  router
}).$mount('#app')
  1. 选择视图展示的位置(所绑定的#app)
  <div id="app">
        <router-view/>//这里将渲染显示组件
  </div>

嵌套关系

如果一个组件里面还有动态变化的各种组件,那么就形成了路由嵌套关系!

当我们的组件里面是这样:

const Foo = {
  template: `
    <div class="user">
      <h2>User {{ $route.params.id }}</h2>
      //我也有内嵌组件
      <router-view></router-view>
    </div>
  `
}

那么在定义映射的是时候,就需要这样,加上儿子children

{ path: '/foo', component: Foo,
    children: [
        {
          // UserProfile 会被渲染在 User 的 <router-view> 中
          path: 'profile',
          component: UserProfile
        },
        {
          // UserPosts 会被渲染在 User 的 <router-view> 中
          path: 'posts',
          component: UserPosts
        }
      ]
    
 },

重定向

所谓重定向,就是你访问A地址的时候,直接跳到B地址

{ path: '/a', redirect: '/b' }

路由守卫

当我们访问一个路由地址的时候,我们都会经过一个大门,这个大门就是这个路由守卫,他能看到你之前的哪里的,想去哪里,大门是否让你通过的数据和行为

  1. 定义了路由,写入钩子函数(上面写过)
const router = new VueRouter({ ... })
router.beforeEach((to, from, next) => {
  // ...
})
router.afterEach((to, from) => {
  // ...finish,访问结束
})
  1. 访问前的钩子函数
router.beforeEach((from ,to,next)=>{
    if (to.path === '/login') {
          next({ path: '/' }) //next函数表示可以GO,还可以带参数哦
        } else {
         next()
      }
    
})


上一篇 下一篇

猜你喜欢

热点阅读