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');  
 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM