vue-router 带参数

2,498 阅读1分钟

1.路由配置

需要添加name属性

new Router(routes:[{
  path:'/',
  name:'xx',
  component:a.vue
}])

2. 路由跳转的四种方式

1.router-link
不带参数,name和path都可以,建议用name
当路径带“/”时,从根路径开始,不带“/”,是从当前路径开始
<router-link :to="{name:'xx'}"></router-link>
<router-link :to="{path:'xx'}"></router-link>
带参数 
params 相当于post请求
<router-link :to="{name:'xx',params:{id:1}}"></router-link>
路由配置:path:/xx/id 或者 path:/xx:id  刷新后id不会消失
不配置路由,刷新后id会消失
html取参:$route.params.id
js取参:this.$route.params.id

query 相当于get请求,参数会显示在url上,可以不配置路由
<router-link :to="name:'xx',query:{id:1}"></router-link>
html取参:$route.query.id
js取参:this.$route.query.id

2. this.$router.push()
不带参数
this.$router.push('xx');
this.$router.push({name:'xx'});
this.$router.push({path:'xx'});
带参数
query传参
this.$router.push({name:'xx',query:{id:1}});
this.$router.push({path:'xx',query:{id:1}});
html取值:$route.puery.id
js取值:this.$route.puery.id

params传参
this.$router.push({name:'xx',params:{id:1}})
路由配置:path:/xx/id 或者 path:/xx:id  刷新后id不会消失
不配置路由,刷新后id会消失
html取参:$route.params.id
js取参:this.$route.params.id
query、params的区别:
query相当于get请求,参数会被连接在url上:‘?id=1’,非重要信息可以这么写
params相当于post请求,刷新后id会消失
注意:parms刷新后,参数会消失,解决,存储在sessionstorage、localStorage中。query刷新不会消失。

3.this.$router.replace() 用法同this.$router.push

4.this.$router.go(n) 向前或向后跳转几个页面,n可正可负

this.$router.push、this.$router.replace、this.$router.go的区别
this.$router.push 
跳转到指定路由,会向history中添加一个记录,点击后退会跳转到上一个页面
this.$router.replace
跳转到指定路由,不会向history中添加一个记录,点击后退时跳转到上上个页面
this.$router.go
向前或向后跳转n个页面