编程式的导航 router.pushhtml
this.$router.push("home"); this.$router.push({ name: 'news', params: { userId: 123 }}) // 传递 this.$route.params.userId // 获取 this.$router.push({path: '/transport/dispatch', query: {paicheNo: obj.paicheNo}}) // 传递 this.$route.query.paicheNo // 获取
声明式的导航
<router-link tag="li" // 渲染为 li标签 默认是 a标签 :to="{name:'city',query:{id:item.id},params:{cityName:item.name}}"> {{item.name}} </router-link>
查询参数搭配query,刷新页面数据不会丢失**vue
一个组件中准备了三个出口react
<router-view class="view one"></router-view> <router-view class="view two" name="a"></router-view> <router-view class="view three" name="b"></router-view>
对于同一个路由 一个视图出口须要一个组件渲染 三个出口就须要三个 下边是具体的配置 注意 components (此时是要加s的)nginx
const router = new VueRouter({ routes: [ { path: '/', components: { default: Foo, a: Bar, b: Baz } } ] })
重定向也是经过routes 配置来完成的 下边的例子是从 /a 重定向到 /bapache
const router = new VueRouter({ routes: [ {path: '/a', redirect: '/b'} ] })
重定向的目标也能够是一个命名的路由编程
const router = new VueRouter({ routes: [ {path: '/a', redirect: {name: 'foo'}} ] })
甚至是一个 function 动态的return从定向的目标后端
const router = new VueRouter({ routes: [ {path: '/a', redirect: to => { // 方法接收目标路由做为参数 // return 重定向饿 字符串路径或路径对象均可以 }} ] })
const router = new VueRouter({ routes: [ {path: '/a', component: Foo, alias: '/b'} ] })
用建立好的实例调用 beforeRouterEnter 守卫中传递给 next 的回调函数服务器
全局前置守卫app
const router = new VueRouter({....}) router.beforEach((to, from, next) => { // to 即将进入的目标路由对象 // from 当前导航正要离开的 路由对象 // next 是一个 function 必需要调用一下 next() })
全局解析守卫
router.beforeResolve((to, from) => { // })
全局后置守卫
router.afterEach((to, from) => { // 此时没有了 next 函数 })
路由独享的守卫
const router = new VueRouter({ routes: [ { path: 'foo', component: Foo, beforeEnter: (to, from, next) => { } } ] })
组件内的守卫 (定义的位置和组件的生命周期平级)
const Foo = { template: `...`, beforeRouterEnter (to, from, next) { // 在组件的对应路由被 confirm 前调用 // 不能获取 组件的 this 由于当此守卫执行时 组件实例尚未建立 下方法能够访问组件实例 next(vm => { // 经过 vm 访问组件的实例 }) }, beforeRouterUpdate (to, from, next) { // 当前路由改变 可是该组件被复用时 调用 // 举例来讲,对于一个带有动态参数的路径 /foo/:id,在 /foo/1 和 /foo/2 之间跳转的时候, // 因为会渲染一样的 Foo 组件,所以组件实例会被复用。而这个钩子就会在这个状况下被调用。 // 能够访问组件的 this }, beforeRouteLeave (to, from, next) { // 导航离开该组件的对应路由时调用 // 能够访问组件实例 `this` } }