文章目录
1、router、routes、route的区别
- router: 是全局路由的实例。可以由它来导航到具体的路由,如:$router.push() 方式
- routes:指创建vue-router路由实例的配置项。用来配置多个route路由对象, 接受的是数组。
- route: 是当前的路由对象,包含了当前 URL 解析得到的信息。包含当前的路径,参数,query对象等。
2、路由配置
2.1 安放路由出口
// 如果router 里面有嵌套,那么router-view 里面也会有嵌套
<router-view></router-view>
2.2 动态路由
// 使用this.$route 获取
{ path: '/User/:id', component: User, name: 'UserPage' }
// 参数属性(props)传递
{ path: '/User/:id', props: {name: ''}, component: User, name: 'UserPage' }
// 进阶应用
function func({ params, query }) {
return {
id: params.id,
msg: params.msg,
foo: query.foo
};
}
{ path: '/User/:id', props: func, component: User, name: 'UserPage' }
2.3 路由跳转
// 由于动态路由也是传递params的,所以在 this.$router.push() 方法中 path不能和params一起使用,
// 否则params将无效。需要用name来指定页面。
this.$router.push({name: 'UserPage', params: {id: 'id'}})
// 传递查询参
this.$router.push({path: '/User/id', query: {age: '18'}}) // url 末端会变为 ?age=18
3、重定向 redirect
const router = new Router({
routes: [
{ path: '/', redirect: '/Home'}, // 这样进/ 就会跳转到/home
{ path: '/Home', component: Home }
]
})
4、嵌套路由
import Home from './components/Home.vue'
import Info from './components/Info.vue'
const router = new Router({
routes: [
{ path: '/Home', component: Home,
children: [
{ path: 'Info', component: Info}
]
}
]
})
5、路由懒加载(异步路由)
通过懒加载就不会一次性把所有组件都加载进来,而是当你访问到那个组件的时候才会加载那一个。对于组件比较多的应用会提高首次加载速度。
const Home = () => import('./components/Home.vue')
const Info= () => import('./components/Info.vue')
const router = new Router({
routes: [
{ path: '/Home', component: Home,
children: [
{ path: 'Info', component: Info}
]
}
]
})
6、路由守卫
1、全局 beforeEach
const router = new Router({
routes: [
{ path: '/Home', component: Home,
children: [
{ path: 'Info', component: Info}
]
}
]
})
router.beforeEach((to, from, next) => {
if (to.path !== '/login') {
if (window.isLogin) {
next()
} else {
next('/login?redirect='+to.path)
}
} else {
next()
}
})
exprot default router
2、路由独享守卫 beforeEnter
const router = new Router({
routes: [
{ path: '/Home', component: Home,
beforeEnter(to, from, next){
if (to.path !== '/login') {
if (window.isLogin) {
next()
} else {
next('/login?redirect='+to.path)
}
} else {
next()
}
},
children: [
{ path: 'Info', component: Info}
]
}
]
})
exprot default router
3、组件内的守卫 beforeRouteEnter
const Foo = {
template: `...`,
beforeRouteEnter(to, from, next) {
// 在渲染该组件的对应路由被 confirm 前调用
// 不!能!获取组件实例 `this`
// 因为当守卫执行前,组件实例还没被创建
}
}
// 不过,你可以通过传一个回调给 next来访问组件实例。
// 在导航被确认的时候执行回调,并且把组件实例作为回调方法的参数。
beforeRouteEnter (to, from, next) {
next(vm => {
// 通过 `vm` 访问组件实例
})
}
7、路由监测变化
监听到路由对象发生变化,从而对路由变化做出响应
const user = {
template:'<div></div>',
watch: {
'$route' (to,from){
// 对路由做出响应
// to , from 分别表示从哪跳转到哪,都是一个对象
// to.path ( 表示的是要跳转到的路由的地址 eg: /home );
}
}
}
// 多了一个watch,这会带来依赖追踪的内存开销,
// 修改
const user = {
template:'<div></div>',
watch: {
'$route.query.id' {
// 请求个人描述
},
'$route.query.page' {
// 请求列表
}
}
}