今天汇总一下vue中都是怎么进行路由跳转和路由传参的。vue-router是根据window.history的API进行封装,如果你了解
window.history`,那么vue-router 路由对您来说就比较简单了。
window.history 和 vue-router api 对比:
window.history API | vue-router API |
---|---|
window.history.replaceState | router.push |
window.history.replaceState | router.replace |
window.history.go | router.go |
名称 | 描述 |
---|---|
path | 当前路由的路径,解析为绝对路径 |
name | 当前路由的名称 |
params | 一个对象,包含动态片段和全匹配片段,如果没有路由参数,就是一个空对象 |
query | 查询参数 |
声明式:
//静态
<router-link to="/"></router-link>
//动态
<router-link :to="{path:'/'}"></router-link>
编程式:
//route path == home
this.$router.push('/home')
//route path == /home
this.$router.push({path:'/home'})
// 路由route name == user
this.$router.push({name:'user'})
//传参 this.$route.query.id。path -> query
this.$router.push({path:'user',query:{id:1}})
//命名路由传参 this.$route.params.id。name->params
this.$router.push({name:'user' ,params:{id:1}})
//动态路由
const uid = 1
router.push({ name: 'user', params: { uid }}) // -> /user/1
router.push({ path: `/user/${uid}` }) // -> /user/1
//替换当前路由
router.replace({ path: '/home' })
router.push({ path: '/home', replace: true })
//当前history记录前进或后退。正数向前进,负数想后退。
router.go(-1) // 后退1步
router.go(3) // 前进3步