vue-router 实现跳转的方式

vue-router 除了router-link 怎么实现跳转?

     1) router-link 实现方式

//1. 不带参数
 
<router-link :to="{name:'home'}"> 
<router-link :to="{path:'/home'}"> //name,path都行, 建议用name

//2.带参数

<router-link :to="{name:'home', params: {id:1}}">


// params传参数 (类似post)
// 路由配置 path: "/home/:id" 或者 path: "/home:id"
// 不配置path ,第一次可请求,刷新页面id会消失
// 配置path,刷新页面id会保留

// html 取参 $route.params.id
// script 取参 this.$route.params.id

    2)  this.$router.push() (函数里面调用) 

1.  不带参数
 
this.$router.push('/home')
this.$router.push({name:'home'})
this.$router.push({path:'/home'})
 
 
 
2. query传参 
 
this.$router.push({name:'home',query: {id:'1'}})
this.$router.push({path:'/home',query: {id:'1'}})
 
// html 取参  $route.query.id
// script 取参  this.$route.query.id
 
 
 
3. params传参
 
this.$router.push({name:'home',params: {id:'1'}})  // 只能用 name
 
// 路由配置 path: "/home/:id" 或者 path: "/home:id" ,
// 不配置path ,第一次可请求,刷新页面id会消失
// 配置path,刷新页面id会保留
 
// html 取参  $route.params.id
// script 取参  this.$route.params.id
 
 
 
4. query和params区别
query类似 get, 跳转之后页面 url后面会拼接参数,类似?id=1, 非重要性的可以这样传, 密码之类还是用params刷新页面id还在
 
params类似 post, 跳转之后页面 url后面不会拼接参数 , 但是刷新页面id 会消失

  

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

在vue.js中想要跳转到不同的 URL,需要使用 router.push 方法。这个方法会向 history 栈添加一个新的记录,当用户点击浏览器后退按钮时,则回到之前的 URL。

设置 replace 属性(默认值: false)的话,当点击时,会调用 router.replace() 而不是 router.push(),于是导航后不会留下 history 记录。即使点击返回按钮也不会回到这个页面。

  


     4)   this.$router.go(n) ()

this.$router.go(n)
向前或者向后跳转n个页面,n可为正整数或负整数

  

     5)this.$router.resolve()跳转打开新的窗口  


官方文档中说 v-link 指令被 <router-link> 组件指令替代,且 <router-link> 不支持 target="_blank" 属性,如果需要打开一个新窗口必须要用<a>标签,但事实上vue2版本的 <router-link> 是支持 target="_blank" 属性的(tag="a"),如下:

<router-link target="_blank" :to="{path:'/home',query:{id:'1'}}">新页面打开home页</router-link>

 

    有些时候需要在单击事件或者在函数中实现页面跳转,那么可以借助router的示例方法,通过编写代码实现。我们常用的是 $router.push 和 $router.go 但是vue2.0以后,这种方式就不支持新窗口打开的属性了,这个时候就需要使用this.$router.resolve,如下:

 

let routeUrl = this.$router.resolve({ path: "/register" }); window.open(routeUrl.href, '_blank');  
 
posted @ 2020-07-13 12:03  水晶草  阅读(8245)  评论(0编辑  收藏  举报