vue路由vue-router

1.同步路由

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

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

  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中

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

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

4.嵌套路由

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.pushState

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,实现路由组件的懒加载


 
原文地址:https://www.cnblogs.com/cxdxm/p/6652674.html