Vue Router (vue2.0)

一、路由的三个要素

  1. 映射表,路由map
// index.js 文件
Vue.use(Router)
export default new Router({
    mode: 'history',               // 开始 HTML5 模式,自带历史记录
    routes: [
      {
          path: '/apple',          // 路由
          component: Apple         // 组件,需import引入
      },
      {
          path: '/banana',
          component: Banana
      }
    ]
})
  1. 展现位置,
    通常配合做缓存

    

  1. 页面中跳转,不再使用 标签
LinkToApple

二、路由参数

  1. 传递
routes: [
    {
        path: '/',
        component: Hello
    },
    {
        path: '/apple/:color/detail/:type',   // 设置参数
        component: Apple
    }
]

http://localhost:8080/apple/green/detail/fruit
注:设置了参数后,则必须传入参数,否则路由访问失败

  1. 接收
    通过this.$route.params来接收参数

{{ $route.params.color }}

{{ $route.params.type }}

... console.log(this.$route.params)

三、路由嵌套

routes: [
    {
        path: '/',
        component: Hello
    },
    {
        path: '/apple',
        component: Apple,
        children: [                      // 定义子路由
            {
                  path: 'green',
                  component: GreenApple,
             }
        ]
    }
]
  1. 子路由只需再写一个 children 数组
  2. 而接受子路由对应的component需要在其分支根节点Apple 中使用

四、导航

  1. 声明式导航,如LinkToApple
  2. 编程式导航
    router.push({path: 'apple'}) // 指定到特定的页面

五、 命名视图




routes: [
    {
        path: '/',
        component: {
            viewA: Apple,                 // 将组件Apple 赋 viewA
            viewB: RedApple               // 将组件RedApple 赋 viewB
        } 
    },
    {
        path: '/apple/:color/detail/:type',   // 设置参数
        component: Apple
    }
]

六、 重定向

    routes: [
      {
          path: '/',
          redirect: '/apple'      // 重定向到 /apple 路径
      }
      {
          path: '/apple',          // 路由
          component: Apple         // 组件,需import引入
      }
    ]

你可能感兴趣的:(Vue Router (vue2.0))