1. 程式人生 > >vue的params和query兩種傳參方式及URL的顯示

vue的params和query兩種傳參方式及URL的顯示

路由配置:

 // 首頁
    {
      path: '/home',
      name:'home',
      component:Home
    },
 // 行情
     {
      path: '/markets',
      name:'market',
      component:Market
    },

query傳值和接收方式:

傳值 

//第一種方式(字串方式) 
this.$router.push('/markets?id=1&name=飯飯') 

//第二種方式(path方式) 
this.$router.push({path:'/markets',query:{id:1,name:'飯飯'}}) 

//第三種方式(name方式) 
this.$router.push({name:'market',query:{id:1,name:'飯飯'}})

 URL顯示:

http://localhost:19091/#/markets?id=1&name=fanfan

 接收資料

console.log(this.$route.query.id); // 1
console.log(this.$route.query.name);// 飯飯

 

params傳值和接收方式:

傳值

//第一種方式
this.$router.push('/markets/1/飯飯')
//第二種方式
this.$router.push({path:'/markets',params:{id:1,name:'飯飯'}})

URL顯示

//第一種方式:(此時引數值在url種顯示)
http://localhost:19091/#/markets/1/飯飯

//第二種方式:(此時引數及引數值都不在url種顯示)
http://localhost:19091/#/markets

對於第一種方式的路由需要改為下邊的配置,第二種方式不需要修改路由

   // 首頁
    {
      path: '/home',
      name:'home',
      component:Home
    },
     // 行情
     {
      path: '/markets/:id/:name',
      name:'market',
      component:Market
    },

接收資料

console.log(this.$route.params.id);// 1
console.log(this.$route.params.name);//飯飯

總結:query和params傳參方式不同之處在於,query傳參會在url中顯示引數以及引數值,params方式則不顯示或者只顯示對應值,且以‘/’方式顯示,params方式不能用path方式傳遞引數,接收方式也