Node.js

Vue Router (vue2.0)

2017-03-29  本文已影响198人  _Wake

一、路由的三个要素

  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. 展现位置,<router-view>
    通常配合<keep-alive>做缓存
<keep-alive>
    <router-view></router-view>
</keep-alive>
  1. 页面中跳转,不再使用 <a> 标签
<router-link :to="{path: '/apple'}">LinkToApple</router-link>

二、路由参数

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

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

  1. 接收
    通过this.$route.params来接收参数
<p>{{ $route.params.color }}</p>
<p>{{ $route.params.type }}</p>
...
console.log(this.$route.params)

三、路由嵌套

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

四、导航

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

五、 命名视图

<router-view name="view-a"></router-view>
<router-view name="view-b"></router-view>

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引入
      }
    ]
上一篇下一篇

猜你喜欢

热点阅读