vue-router
router.push(location)
想要导航到不同的 URL,则使用 router.push
方法。这个方法会向history
栈添加一个新的记录,所以,当用户点击浏览器后退按钮时,则回到之前的 URL。
当你点击 <router-link>
时,这个方法会在内部调用,所以说,点击 等同于调用 router.push(…)
。
声明式:<router-link :to="...">
编程式:router.push(...)
该方法的参数可以是一个字符串路径,或者一个描述地址的对象。
// 参数可以是字符串
this.$router.push('home')
// 参数也可以是个对象
this.$router.push({ name: 'home'})
接下来带参数的
this.$router.push({
name: 'home',
params: {
id: 3.3
}
})
// 接收参数为
console.log(this.$route.params.id)
使用params传参数的时候,this.$router.push({name: '这里一定要是name', parms: {}})
因为params
只能用name
来引入路由,如果这里写成了path
,接收参数页面会是undefined
!!!
不知道为什么此方式无效了,本地测试Route with name 'home' does not exist
版本如图
//query
this.$router.push({
path: '/home/sheap',
query: {
id: 3.2
}
})
使用query传参数的时候,this.$router.push({path: '这里一定要是path', query: {}})
因为query
只能用path
来引入路由,如果这里写成了name
,接收参数页面会是http://localhost:8080/?id=3.2
亲测!!!
重点在于, push的时候是router
。 接收的时候用的是route
一定要看清楚!!!
replace
类型: boolean
默认值: false
设置 replace 属性的话,当点击时,会调用 router.replace() 而不是 router.push(),于是导航后不会留下 history 记录。即使点击返回按钮也不会回到这个页面。
//加上replace: true后,它不会向 history 添加新记录,
//而是跟它的方法名一样 —— 替换掉当前的 history 记录。
this.$router.push({path: '/home', replace: true})
//如果是声明式就是像下面这样写:
<router-link :to="..." replace></router-link>
// 编程式:
router.replace(...)
参考:https://segmentfault.com/a/1190000012735168
https://blog.youkuaiyun.com/qq_30114149/article/details/78416457