一、vue-router介绍
vue-router是vue官方提供的一个路由框架,控制页面路由,使用较为方便。
1.路由模式
- hash(浏览器环境默认值),使用 URL hash 值来作路由,支持所有浏览器。
- history:依赖HTML5 History API和服务器配置
-
abstract
: 支持所有 JavaScript 运行环境,如 Node.js 服务器端。如果发现没有浏览器的 API,路由会自动强制进入这个模式。
2.动态路由
路由中可以配置参数,如下所示:
const User = {
template: '<div>User</div>'
}
const router = new VueRouter({
routes: [
// 动态路径参数 以冒号开头
{ path: '/user/:id', component: User }
]
})
路由中的参数都可以通过 $route.params来获取;如果URL中有查询参数,可以使用$route.query。
关于路由优先级:
有时候,同一个路径可以匹配多个路由,此时,匹配的优先级就按照路由的定义顺序:谁先定义的,谁的优先级就最高。
3.路由嵌套
const router = new VueRouter({
routes: [
{ path: '/user/:id', component: User,
children: [
{
// 当 /user/:id/profile 匹配成功,
// UserProfile 会被渲染在 User 的 <router-view> 中
path: 'profile',
component: UserProfile
},
{
// 当 /user/:id/posts 匹配成功
// UserPosts 会被渲染在 User 的 <router-view> 中
path: 'posts',
component: UserPosts
}
]
}
]
})
4.编程式导航
除了使用<router-link :to="...">的方式来定义路由链接,还可以使用编程式的导航,router.push(...)。在 Vue 实例内部,可以通过 $router
访问路由实例。因此可以调用 this.$router.push来完成。
const userId = 123
router.push({ name: 'user', params: { userId }}) // -> /user/123
router.push({ path: `/user/${userId}` }) // -> /user/123
// 这里的 params 不生效,如果提供了 path,params 会被忽略
router.push({ path: '/user', params: { userId }}) // -> /user
router.go(n) //这个方法的参数是一个整数,意思是在 history 记录中向前或者后退多少步
router.back() //后退
router.forward() //前进
5.导航守卫
vue-router
提供的导航守卫主要用来通过跳转或取消的方式守卫导航。有多种机会植入路由导航过程中:全局的, 单个路由独享的, 或者组件级的。
详细参考地址 vue-router导航守卫
二、vue-router的使用
使用npm安装完vue-router后,需要import vue-router,然后进行路由配置,就可以使用了。
import VueRouter from 'vue-router'
Vue.use(VueRouter)
let router = new VueRouter({
mode: 'history',
routes: [
{
path: '/',
component: IndexPage
},
{
path: '/orderList',
component: OrderListPage
}
]
})
new Vue({
el: '#app',
router,
components: {Layout},
template: '<Layout/>'
})
在template中通过 router-link 和router-view来进行控制。
router-link是一个组件,它默认会被渲染成一个带有链接的a标签(可以通过配置 tag
属性生成别的标签),通过to属性指定链接地址,这个属性必须设置,否则路由无法生效。
router-view这个组件是用来渲染匹配到的路由,匹配到的路由就会显示在router-view所在的地方
<template>
<div class="detail-wrap">
<div class="detail-left">
<div class="product-board">
<img :src="productIcon">
<ul>
<router-link v-for="item in products" :to="{ path: item.path }" tag="li" active-class="active" :key="item.name">
{{ item.name }}
</router-link>
</ul>
</div>
</div>
<div class="detail-right">
<keep-alive>
<router-view></router-view>
</keep-alive>
</div>
</div>
</template>
vue-router官方文档 https://router.vuejs.org/guide