头图

一、起步

<div id="app">
      <!-- 使用router-link组件来导航,通过传入to属性指定链接,最终router-link会被渲染成一个a标签 -->
      <router-link to="/foo">Go to Foo</router-link>
      <router-link to="/bar">Go to Bar</router-link>
      <div class="router-container">
        <!-- 路由匹配到的组件将渲染在这里 -->
        <router-view></router-view>
      </div>
    </div>
    <script>
      //1、定义路由组件(引入路由组件)
      const Foo = {
        template: '<div class="foo"><h2>Foo</h2></div>'
      }
      const Bar = {
        template: '<div class="bar"><h2>Bar</h2></div>'
      }
      //2、定义路由
      const routes = [
        {
          path: '/foo',
          component: Foo
        },
        {
          path: '/bar',
          component: Bar
        }
      ]

      //3、创建router实例
      const router = new VueRouter({
        routes
      })

      let vm = new Vue({
        el: '#app',
        router
      })
</script>

二、动态路由
给路由路径设置参数

//定义路由组件(或引入路由组件)
const User ={
  template: '<div>User {{$route.params.id}}</div>',
  //因参数发生变化,组件会复用,则组件生命周期钩子不会被调用,通过以下两种方法监测路由改变
  //方法一:使用watch监测$route
  //watch:{
  //  $route(to,from){
  //    //对路由变化做出响应
  //  }
  //} 
  //方法二:
  beforeRouteUpdate(to,from,next){
    // react to route changes...
    // don't forget to call next()
  }
}
//实例化vue-router
const router = new VueRouter({
  routes:[
    {
      //动态路径参数以:冒号开头
      path: '/user/:id',
      component: User
    }
  ]
})

传入实参的方法

<!--声明式:使用<router-link>组件时,使用:to动态绑定-->
<router-link :to="{path: '/user/'+user.id}">Go to User</router-link>

//编程式:使用router.push时
router.push({name: 'user',params: {id: user.id}})

三、嵌套路由
可以在路由组件中嵌套<router-view>标签,作为子路由的出口

//定义路由组件
cosnt User = {
  template: `<div>
    <h2>User {{$route.params.id}}</h2>
    <router-view></router-view>
  </div>`
}
//定义子路由组件
const UserProfile = {
  template: '<div>user profile</div>'
}

使用children属性配置子组件

const router = new VueRouter({
  routes:[
    {
      path: '/user/:id',
      component: User,
      children:[
        {
          path: '/profile',
          component: UserProfile
        }
      ]
    }
  ]
})

四、编程试的导航
1、router.push()
除了使用<router-link>创建a标签来定义导航链接,我们还可以借助router的实例方法,通过编写代码来切换路由。
想要导航到不同的url,则使用router.push()方法,该方法会向history栈添加一个新的纪录。
当点击<router-link>时,会在内部调用router.push()方法,所以点击<router-link :to="...">等同于调用router.push(...)

router.push()的参数取值如下:

// 字符串
router.push('home')

// 对象
router.push({ path: 'home' })

// 命名的路由
router.push({ name: 'user', params: { userId: '123' }})

// 带查询参数,变成 /register?plan=private
router.push({ path: 'register', query: { plan: 'private' }})

若提供了path,则name会被忽略。因此在定义带动态参数的路由时,若使用params,则必须使用name。to也适用该规则。

router.push({name:'user',params: {user.id}})
router.push({path: `/user/${user.id}`})
//下面的写法,params不会生效
router.push({path:'/user',params:{user.id}})

2、router.replace()
跟router.push()很像,唯一的区别就是它不会向history添加新纪录,而是跟它的方法名一样,替换掉当前history纪录
声明式:

<router-link :to="..." replace>

编程式:

router.replace(...)

3、route.go(n)
参数是一个整数,意思是在history纪录中向前或向后退多少步,类似window.history.go(n)


五、路由命名
使用name属性给route命名,可以通过name链接到该路由

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

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

这两种方法都会把路由导航到/user/123路径


六、命名视图
当需要同级展示多个视图时,而不是嵌套展示时,例如创建一个布局,有sidebar和main两个视图,我们可以在界面中拥有多个单独命名的视图,使用命名来区别。

<router-view></router-view>
<router-view name='sidebar'></router-view>
<router-view name='mainView'></router-view>

多个视图就需要多个组件,确保正确使用components

const router = new VueRouter({
  routes:[
    {
      path: '/',
      components: {
        //未命名的默认为default
        default: HeaderView,
        siderbar: Siderbar,
        mainView: MainView
      }
    }
  ]
})

七、重定向和别名
1、重定向-redirect
重定向:当用户访问/a时,url会被替换成/b,然后匹配路由为/b

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

2、别名-alias
若/a的别名是/b,则当用户访问/b时,url会保持/b,但路由匹配为/a,就像访问/a一样。

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

八、路由组件传参
在组件中使用$route会使之与对应路由形成高度耦合,从而使组件只能在某些特定的url上使用。推荐使用props将组件和路由解耦

const User = {
  template: '<div>User {$route.params.id}</div>'  
}
const router = new VueRouter({
  routes: [
    {
      path: '/',
      component: User,
      props: true
    },
    //对于包含命名视图的路由,必须为每个命名视图添加props
    {
      path:'/user/:id',
      components:{
        default: User,
        sildebar: Sidebar
      },
      props:{
        default: true,
        sidebar: true
      }
    }
  ]
})

props的取值:
1、布尔模式-如果props被设置为true,route.params将会被设置为组件属性
2、对象模式
如果props是一个对象,它会被按原样设置为组件属性

const router = new VueRouter({
  routes: [
    {
      path: '/promotion/from-newsletter',
      component: Promotion,
      props: { newsletterPopup: false }
    }
  ]
})

3、函数模式
可以创建一个函数返回props,这样可以将参数转换成另一种类型,将静态值与基于路由的值结合。

const router = new VueRouter({
  routes: [
    {
      path: '/search',
      component: SearchUser,
      props: route => ({query: route.query.q})
    }
  ]
})

URL /search?q=vue 会将 {query: 'vue'} 作为属性传递给 SearchUser 组件。


Liane
16 声望2 粉丝