做完了Vue项目整理一下,看到网上的一篇博客写的清晰明了,模仿风格也整理一下。
Vue的路由跳转有四种方式:
1.<router-link ></router-link>
2.this.$router.push()
3.this.$router.replace()
4.this.$router.go(n)
一、不带参
1.写在结构中:
name和path都可以,建议用name(这句话从原来博文看来的,自己需要进一步体会)
注意:router-link中的链接如果是从‘/’开始就是从跟路由开始,如果不带‘/’从当前路由开始。
<router-link :to="{name:'home'}"></router-link>
<router-link :to="{path:'/home'}"></router-link>
2.写在方法中:
this.$router.push('/home')
this.$router.push({name:'home'})
this.$router.push({path:'/home'})
二、带参
1:query传参 path
this.$router.push({path:'/AddDocType',query:{id:'1'}})
参数会显示在URL上:http://localhost:8080/AddDocType?id=1
设置路由就是/AddDocType
通过this.$route.query.id获取id
2:query传参 name
this.$router.push({name:'AddDocType',query:{id:'1'}})
参数会显示在URL上:http://localhost:8080/AddDocType?id=1
设置路由就是/AddDocType
通过this.$route.query.id获取id
3:params传参 name(只能用name)
this.$router.push({name:'AddDocType',params:queryData})
http://localhost:8080/AddDocType
设置路由就是/AddDocType/:id 或者/AddDocType:id
配置:id刷新id会保留,不配置:id第一次可以,刷新后id消失
在跳转到的页面中打印this.$route 获取params中传递的参数
3.另一个用法
this.$route.push({path:`/AddDocType/${id}`)
http://localhost:8080/AddDocType/1
设置路由就是/AddDocType/:id
在跳转到的页面中打印this.$route
通过this.$route.params.id获取id
4.
<router-link :to="{name:'home',params:{id:1}"></route-link>
//路由 path:"/hone/:id" 或者"/home:id"
//不配置id,刷新后id消失
//html取参: $route.params.id
//js取参 : this.$route.params.id
<router-link to="{ name:'home',query:{id:1} }"></router-link>
//参数会显示在url后面
//html取参 $route.query.id
//js取参 this.$route.query.id
其他:
1.打开新的浏览器标签页
const newPage = this.$router.resolve({path: `/seller/AddDocType/${id}`})
window.open(newPage.href,'_blank')
取参:this.$route.params
2
this.$router.go(n)介绍:
this.router.go(n) 向前或者向后跳转n个页面,n可为正整数或负整数
区别:
this.$router.push 跳转到指定url路径,并在history栈中添加一个记录,点击后退会返回到上一个页面
this.$router.replace 跳转到指定url路径,但是history栈中不会有记录,点击返回会跳转到上上个页面 (就是直接替换了当前页面)
this.$router.go(n) 向前或者向后跳转n个页面,n可为正整数或负整数