一、router-link
1.不带参数
<router-link :to="{name:'home'}">
<router-link :to="path:'/home'">
注意:
- 建议使用
name的形式
2.带参数
params传参
<router-link :to="{name:'home',params:{id:1}}">
注意:
-
params传参类似post
-
需要在路由配置
path:"/home/:id或者path:"/home:id",如果不配置在刷新页面时参数会丢失
获取值
html 取参 $route.params.id
script 取参this.$route.params.id
注意:
一般来说,使用上面的方法是可以在组件中获取值,但是为了组件有更好的扩展性,可以在组件中使用props来接收,这样既可以节省代码又可以提高组件的扩展性
query传参
<router-link :to="{name:'home', query: {id:1}}">
注意:
-
query传参类似get
-
路由可不配置
获取值
html 取参 $route.query.id
script 取参this.$route.query.id
二、 this.$router.push()
1.不带参数
this.$router.push('/home')
this.$router.push({name:'home'})
this.$router.push({path:'/home'})
注意:这种方式一般在函数里面使用
2.带参数
params传参
this.$router.push({name:'home',params: {id:'1'}})
注意:
-
只能用 name
-
需要路由配置
path: "/home/:id"或者path: "/home:id",否则页面刷新参数会丢失
获取值
html 取参$route.params.id
script 取参this.$route.params.id
query传参
this.$router.push({name:'home',query: {id:'1'}})
this.$router.push({path:'/home',query: {id:'1'}})
获取值
html 取参 html 取参 $route.query.id
script 取参 this.$route.query.id
三、this.$router.repalce()
1.不带参数
this.$router.repalce('/home')
this.$router.repalce({name:'home'})
this.$router.repalce({path:'/home'})
注意:这种方式一般在函数里面使用
2.带参数
params传参
this.$router.repalce({name:'home',params: {id:'1'}})
注意:
-
只能用 name
-
需要路由配置
path: "/home/:id"或者path: "/home:id",否则页面刷新参数会丢失
获取值
html 取参$route.params.id
script 取参this.$route.params.id
query传参
this.$router.repalce({name:'home',query: {id:'1'}})
this.$router.repalce({path:'/home',query: {id:'1'}})
获取值
html 取参 $route.query.id
script 取参 this.$route.query.id
四、this.$router.go(n)
n 可以为正整数也可以为负整数,表示往前或者往后几页
比如, 返回上一页 this.$router.go(-1);
五、replace()与push()的区别
this.$router.push()
跳转到指定url路径,并想history栈中添加一个记录,点击后退会返回到上一个页面
this.$rounter.replace()
跳转到指定url路径,但是history栈中不会有记录,点击返回会跳转到上上个页面 (就是直接替换了当前页面)