前端面試vue-router路由跳轉方式(傳參數)

詳見 vue-router官網

1.router-link

1.1 不傳參

<router-link :to="/home">跳轉</router-link>

1.2 傳參

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

params傳參數 (類似post)

    路由配置 path: "/home/:id" 或者 path: "/home:id"

    不配置path ,第一次可請求,刷新頁面id會消失

    配置path,刷新頁面id會保留

取參數值

    html 取參 $route.params.id

    script 取參 this.$route.params.id

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

query傳參數 (類似get,url後面會顯示參數)

    路由可不配置

取參數值:

    html 取參 $route.query.id

    script 取參 this.$route.query.id

2.this.$router.push() 編程式

2.1不傳參數

this.$router.push('/home');
this.$router.push({name:'home'});
this.$router.push({path:'/home'});

2.2query傳參數

this.$router.push({name:'home',query: {id:'1'}});
this.$router.push({path:'/home',query: {id:'1'}});

取參數同 1.2

    html 取參 $route.query.id

    script 取參 this.$route.query.id

2.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

2.4  query和params區別

query類似 get, 跳轉之後頁面 url後面會拼接參數,類似?id=1, 非重要性的可以這樣傳,

 密碼之類還是用params,

 刷新頁面id還在;

params類似 post, 跳轉之後頁面 url後面不會拼接參數 , 但是刷新頁面id 會消失。

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

4. this.$router.go(n) 

    向前或者向後跳轉n個頁面,n可爲正整數或負整數

區別:

1. this.$router.push

    跳轉到指定url路徑,並想history棧中添加一個記錄,點擊後退會返回到上一個頁面

2. this.$router.replace

    跳轉到指定url路徑,但是history棧中不會有記錄,點擊返回會跳轉到上上個頁面 (就是直接替換了當前頁面)

3. this.$router.go(n)

    向前或者向後跳轉n個頁面,n可爲正整數或負整數

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章