了解VueRouter,这篇解析就够了

核心原理:

将组件 (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()
	  }
    
})


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值