Vue router专为单页应用产生。
1.简单路由,不需要引入功能完整的路由库:

2.添加Vuerouter -》 将组件映射到routes-》 告诉Vuerouter在哪里渲染他们
<router-view>:路由匹配到的组件将渲染在这里
<router-link>:使用router-link组件导航,通过传入to属性来指定链接,被渲染成一个a标签。
采用模块化编程机制(导入Vue,Vuerouter,调用Vue.use(VueRouter)):
1.定义/import组件
- 定义路由(每个路由映射一个组件)
路由列表:
const routes = [{path:'/foo', component:Foo},
{path:'/bar', component:Bar}]
3.创建router实例,传‘routes’配置
const router = new VueRouter({
routes
})
4.创建和挂载根实例。通过router参数注入路由
const app = new Vue({
router
}).$mount('#app')
- 把某种模式匹配到的所有路由,全都映射到同个组件把某种模式匹配到的所有路由,全都映射到同个组件,使用动态路径参数(以:开头),当匹配到一个路由时,参数值被设置到this.$route.params中,可以在组件中使用。
4.嵌套路由
在嵌套的出口中渲染组件,需要在VueRouter 的参数中使用children配置。
5.编程式导航
除了使用<router-link>来定义导航链接,还可以借助router的实例方法。
router.push(location, onComplete? , onAbort?)

6.命名路由:
建立名称标志一个路由,在创建Router实例的routes选项中给某个路由设置名称:name: 'user', 要链接到一个命名路由时,传入name属性。


- 路由重定向
在routes选项中,使用redirect关键字
routes: [{path: '/a', redirect: '/b'},
{path: '/a', redirect: {name:'foo'}} //重定向目标可以是命名的路由
{path: '/a', redirect: to=>{ ...}} //重定向目标也可以是一个方法用于动态返回重定向目标 方法接收目标路由作为参数,返回重定向的字符串路径]
网友评论