vue-router的简单使用

109 阅读1分钟

权威内容查看官方文档

引入

使用npm/yarn进行安装后,在文件中引入

import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

使用

  1. 定义/导入组件

    const Foo = { template: '<div>foo</div>' }
    const Bar = { template: '<div>bar</div>' }
    
  2. 定义路由(表)

    const routes = [
      { path: '/foo', component: Foo },
      { path: '/bar', component: Bar }
    ]
    

    路由表中为对象,每个路由应该映射一个组件

  3. 创建router示例

    为方便区分,routes对应路由表,router对应路由器

    const router = new VueRouter({
      routes // (缩写) 相当于 routes: routes
    })
    
  4. 创建Vue示例

    const app = new Vue({
      router
    }).$mount('#app')
    

    配置options对象的router,注入路由,整个应用都拥有路由功能。

    通过以上操作,我们可以在任意组件中使用 this.$routerthis.$route来分别访问 路由器 和 当前路由。

  5. 在html(template)中使用

    • 导航

       <router-link to="/foo">Go to Foo</router-link>
       <router-link to="/bar">Go to Bar</router-link>
      

      使用 router-link 组件来导航,通过to属性指定跳转链接。<router-link> 默认会被渲染成一个 <a> 标签,且自动设置 class 属性值 .router-link-active

    • 对应组件渲染

      <router-view></router-view>
      或者
      <router-view />
      

      router-view 路由出口,路由匹配到的组件将渲染在这里

路由匹配

  1. 优先级

    有时候,同一个路径可以匹配多个路由,此时,匹配的优先级就按照路由的定义顺序:谁先定义的,谁的优先级就最高。

    简而言之,按顺序

  2. 使用通配符

    {
      // 会匹配所有路径
      path: '*'
    }
    {
      // 会匹配以 `/user-` 开头的任意路径
      path: '/user-*'
    }
    

    由于直接使用 * ,会匹配上所有路由,一般用于处理404情况,且需要放在路由表的最末(由第一点优先级可得)。

    const routes = [
        {…………},
        {…………},
        {
            path: '*',
            component: NotFound
          },
    ]
    
  3. 动态路由匹配

    const routes=[
        {
            path: '/labels/edit/:id',
            component: EditLabel
        }
    ]
    

    使用冒号标记路径参数,当匹配到一个路由时,参数值会被设置到 this.$route.params

    <template>
        <div>用户id:{$route.id}</div>
    </template>