vue路由vue-router

1.同步路由html

  a.引入你想跳转的文件 import payment from './app/payment'vue

  b.在路由里配置你的页面html5

  const router = new VueRouter({
   routes: [
  {name:'payment',path:'/payment',component: payment} //path里的路径是指你浏览器显示的路径(例如http://localhost:9000/#/payment)
  })
 c.调用你的路由(个人实例代码是写在一个方法里的)
  
payMent(){
   var obj={total:this.totalPrice}

    router.push({
       name:"payment",
     params:obj //若是须要传参时写(这必须传对象,否则界面会获取不到你想要传的值
) 调用传过来的参数 TitleValue: this.$route.params.item.name,
    })
   }
2.异步路由
  使用异步路由不须要引入文件,也就是同步路由中的a步骤不须要,
  a.配置你要跳转的界面路由
    const router = new VueRouter({
      routes: [{name:'payment',path:'/payment',component:(resolve)=>{
  
        require.ensure(['./app/payment'],()=>{

          resolve(require('./app/payment'))
          })
   }},

   ],
  })
3.动态路由的配置
const User = {
  template:'<div>User</div>'  
}

const router = new VueRouter({
   routes:[
      //动态路径参数,以冒号开头
      {path:'/user/:id',component:User}    
    ] 
})
   <router-link to="/user/bar">/user/bar</router-link> 
 

能够在路由中设置多段路径参数,对应的值会设置到$route.params中webpack

模式 匹配路径 $route.params
/user/:username /user/evan {username:'even'}
/user/:username/post/:post_id /user/evan/post/123 {username:'even',post_id:123}

当两个路由使用同一组件的时候,切换时原来的组件实例会被复用。由于两个路由都渲染同个组件,比起销毁再建立,复用则显得更加高效。不过,这也意味着组件的生命周期钩子不会再被调用。web

4.嵌套路由vue-router

const router = new VueRouter({
   routes: [
      {path: '/user/:id',component: User,
         children: [
           {
              //当/user/:id/profile匹配成功
              //UserProfile会被渲染在User的<router-view>中
              path:'profile',
              component:UserProfile
           },
           {
              //当/user/:id/posts匹配成功
              //UserPosts会被渲染在User的<router-view>中
              path: 'posts',
              component: UserPosts
           }
         ]
      }    
   ]
})
  要注意,以/开头的嵌套路径会被看成根路径。这让你充分的使用嵌套组件而无须设置嵌套的路径

5.命名路由编程

const router = new VueRouter({
    routers: [
       {
         path: '/user/:userId',
         name: 'user',
         component:User 
       }
     ] 
})

<router-link :to="{ name: 'user', params: { userId: 123 }}">User</router-link>

router.push({ name: 'user', params: { userId: 123 }})

6.编程式的导航浏览器

声明式 编程式
<router-link :to=''>

router.push()  //window.history.pushStateapp

router.replace()//window.history.replaceState异步

导航到不一样的url时,router.push方法会向history栈添加一个新的记录,因此,当用户点击浏览器后腿按钮时,则回到以前的url。router.replace()跟push很像,可是它不会向history添加新记录,而是跟它的方法名同样替换掉当前的history记录

//字符串
router.push('home')
//对象
router.push({path:'home'})
//命名的路由
router.push({name:'user',params:{userId:123}})
//带查询参数,生成/register?plan=private
router.push({path:'register',query:{plan:'private'}})
 

router.go(n)相似于window.history.go(n)

//在浏览器记录中前进一步,等同于history.forward()
router.go(1)
//后退一步记录,等同于history.back()
router.go(-1)
//前进3步记录
router.go(3)

7.命名视图

不写名字的默认为default,使用时components(带上s)

<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>
const router = new VueRouter({
 routes:[
  {
    path:'/',
    components:{
      default:Foo,
       a:Bar,
       b:Baz
     }
  }
 ]
})    

8.重定向

/a重定向到/b
const router = new VueRouter({
   routes: [
     {path:'a',redirect:'/b'}
   ]
})

//重定向的目标也能够是一个命名的路由
const router = new VueRouter({
  routers: [
    {path:'/a',redirect:{name:'foo'}} 
  ]
})
//也能够是一个方法,动态返回重定向目标
const router = new VueRouter({
routes: [
{path:'/a',redirect: to =>{
//方法接收目标路由做为参数
//return 重定向的字符串路径/路径对象
}}
]
})

9.别名

 
const router =new VueRouter({
  routes:[
    {path:'/a',component:A,alias:'/b'}
   ]
})
 

10.导航钩子:路由发生变化是触发

钩子方法的参数介绍:

1.to(route):即将要进入的目标路由对象

2.from(route):当前导航正要离开的路由

3.next(Function):必定要调用该方法来resolve这个钩子。执行效果依赖next方法的调用参数(确保要调用next方法,不然钩子就不会被resolved)

   3.1.next():进行管道中的下一个钩子。若是所有钩子执行完了,则导航的状态就是confirmed(确认的)

   3.2.next(false):中断当前的导航。若是浏览器的URL改变了(多是用户手动或浏览器后腿按钮),那么URL地址会重复到from路由对应的地址

   3.3.next('/')或next({path:'/'}):跳转到一个不一样的地址。当前的导航被中断,而后进行一个新的导航

全局钩子

const router = new VueRouter({})
router.beforeEach((to,from,next)=>{})
一样能够注册一个全局的after钩子,不过它不像before钩子那样,它没有next方法
router.afterEach(route=>{})

某个路由独享的钩子

const router = new VueRouter({
   routes:[
     {path:'/foo',
       component:Foo,
      beforeEnter:(to,from,next)=>{}
     }
   ]
})

组件内的钩子

beforeRouteEnter:它不能访问this,由于钩子在导航确认前被调用,所以即将登场的新组件还没被建立,。不过你能够经过传一个回调给next来访问组件实例。在导航被确认的时候执行回调,而且把组件实例做为回调方法的参数

      beforeRouteEnter(to,from,next){next(vm=>{//经过vm访问组件实例})}

beforeRouteUpdate

beforeRouteLeave:直接访问this。这个leave钩子一般用来禁止用户在还未保存修改以前忽然离开。能够经过next(false)来取消导航

const Foo = {
  template:'.....',
  beforeRouteEnter(to,from,next){
    //在渲染该组件的对应路由被confirm前调用
    //不能获取组件实例this
   //由于钩子执行前,组件实例还没被调用
  },
  beforeRouteUpdate(to,from,next){
   //在当前路由改变,可是该组件被复用时调用
  //举例来讲,对于一个带有动态参数路径/foo/:id,在/foo/1和/foo/2之间跳转的时候,
  //因为会渲染一样的Foo组件,所以组件实例会被复用。而这个钩子就会在这个状况下被调用。
  //能够访问组件实例this
  },
   beforeRouteLeave(to,from,next){
     //导航离开该组件的对应路由时调用
    //能够访问组件实例this
  }
}

路由元信息:详细查看API

11.过渡动效

全局:

 

<transition>
  <router-view></router-view>
</transition>

 

单个路由的过渡:需设置不一样的name

const Foo = {
   template:`<transition name="slide">
                     <div class="foo"></div>
                   </transition>
                 `
}

const Bar= {
   template:`<transition name="fade">
                     <div class="bar"></div>
                   </transition>
                 `
}

基于路由的动态过渡

//使用动态的transition name
<transition :name="transitionName">
   <router-view></router-view>
</transition>

//接着在父组件内
//watch $route 决定使用哪一种过渡
watch:{
   '$route'(to,from){
        const toDepth = to.path.split('/').length
        const fromDepth = from.path.split('/').length
        this.transitionName = toDepth<fromDepth ? 'slide-right' : 'slide-left'
   }
}

 数据获取

12.滚动行为:vue-router可让你自定义切换时页面如何滚动(注意:这个功能只在html5 history模式下可用)

滚动的方法scrollBehavior:

  接收的参数:路由对象(to from),第三个参数savedPosition当且仅当popstate导航(经过浏览器的前进/后退按钮触发)时才可用

     savedPosition方法返回滚动位置的对象信息:

      {x:number,y:number}   {selector:string}  (若是返回一个布尔假值,或空对象,就不会发生滚动)  

 
使用例子:
const router = new VueRouter({
   routes:[...],
   scrollBehavior(to,from,savedPosition){
       //return 指望滚动到哪一个的位置
   } 
})

不会发生滚动的例子:
scrollBehavior(to,from,savePosition){
  return {x:0,y:0}  
}

按下前进/后退时:
scrollBehavior(to,from,savedPosition){
 if(savePosition){
   return savedPosition
 }else{
    return {x:0,y:0}
 }
}

模拟滚动到锚点的行为:
scrollBehavior(to,from,savedPosition){
  if(to.hash){
    return{
       selector:to.hash
    }
  }
}
 

13.路由懒加载:结合Vue的异步组件和webpack的code splitting feature,实现路由组件的懒加载

相关文章
相关标签/搜索