1. 程式人生 > >vue中頁面跳轉傳值的幾種方式

vue中頁面跳轉傳值的幾種方式

一、router-link

URL路徑:http://localhost:8081/#/test?userid=1

<router-link :to="{path:'/test',query: {userid: id}}">跳轉</router-link>

收:

var id = this.$route.query.userid

注意:

  • to前面一定要加 : ,一定要記得加!記得加!加!
  • to後面 { 中的name值(這裡是userid)要與路由中的name值一致

### 二、this.$router.push()

1、使用path+query

URL路徑:http://localhost:8081/#/selectCate?userid=1

發:

var id = 1;
this.$router.push({path:'/selectCate',query:{userid:id}});

收:

var id = this.$route.query.userid;

這裡注意接收到的是字串,但id是數字,所以需要轉化一下:

var id = parseInt(this.$route.query.userid);

2、使用name+params

URL路徑:http://localhost:8081/#/selectCate?userid=1

發:

var id = 1;
this.$router.push({name:'selectCate',params:{userid:id}});

收:

var id = this.$route.params.userid;

總結:使用query,傳輸的值會在url後面以引數的形式顯示出來,而params不會。

三、LocalStorage存值

總這麼跳來跳去的,還每次都帶個’包’走,還不如把這些資料存一下,用的時候取出來。
怎麼做!看這裡!
localStorage使用總結
其實很簡單:

//儲存userid至記憶體
var userID = 1;
localStorage.setItem('storeID',JSON.stringify(userID));

//取,注意這裡取出的是字串。
this.userID= JSON.parse(localStorage.userID);