轉:vue嵌套路由-params傳遞參數

轉載:https://blog.csdn.net/k491022087/article/details/70232965

在嵌套路由中,父路由向子路由傳值除了query外,還有params,params傳值有兩種情況,一種是值在url中顯示,另外一種是值不顯示在url中。

1、顯示在url中

index.html

[html] view plain copy
  1. <div id="app">  
  2.     <!-- router-view 路由出口, 路由匹配到的組件將渲染在這裏 -->  
  3.     <router-view></router-view>  
  4.     </div>  

main.js params傳值是通過 :[參數值] 如path: "/home/game/:num"

[html] view plain copy
  1. import Vue from 'vue'  
  2. import VueRouter from 'vue-router'  
  3. Vue.use(VueRouter)  
  4. //引入兩個組件  
  5. import home from "./home.vue"  
  6. import game from "./game.vue"  
  7. //定義路由  
  8. const routes = [  
  9.     { path: "/", redirect: "/home" },//重定向  
  10.     {  
  11.         path: "/home", component: home,  
  12.         children: [  
  13.             { path: "/home/game/:num", component: game }  
  14.         ]  
  15.     }  
  16. ]  
  17. //創建路由實例  
  18. const router = new VueRouter({routes})  
  19.   
  20. new Vue({  
  21.     el: '#app',  
  22.     data: {  
  23.         id:123,  
  24.     },  
  25.     methods: {  
  26.     },  
  27.     router  
  28. })  
home.vue 在home中具體的值就跟在路徑後面,如 “/home/game/123”,也就是說傳遞給子路由的值就是 123

[html] view plain copy
  1. <template>  
  2.     <div>  
  3.         <h3>首頁</h3>  
  4.         <router-link to="/home/game/123">  
  5.             <button>顯示</button>  
  6.         </router-link>  
  7.         <router-view></router-view>  
  8.     </div>  
  9. </template>  
game.vue 在子路由中,通過 this.$route.params.參數名來接受傳遞過來的值

[html] view plain copy
  1. <template>  
  2.     <h3>王者榮耀{{ this.$route.params.num }}</h3>  
  3.     </template>  



2、不顯示在url中,如果在PC端將傳遞的值顯示在url中,這樣無形中就存在安全隱患,如果客戶不小心修改了url那樣就會出錯,移動端就無所謂了,如何才能不顯示在url中,同樣很簡單,但是需要給映射的路徑起一個別名,通過name來取別名

同樣只需將上面的main.js中的定義路由改爲如下樣子,在子路由中通過name來給路徑其一個game1的別名。

[html] view plain copy
  1. //定義路由  
  2. const routes = [  
  3.     { path: "/", redirect: "/home" },//重定向  
  4.     {  
  5.         path: "/home", component: home,  
  6.         children: [  
  7.             { name: "game1", path: "/home/game/", component: game }  
  8.         ]  
  9.     }  
  10. ]  

home.vue 中router-link修改爲:to="{ name:'game1', params: {num: 123} }" params中是要傳遞的參數,這樣傳遞的參數就不會顯示在url中。

[html] view plain copy
  1. <template>  
  2.     <div>  
  3.         <h3>首頁</h3>  
  4.         <router-link :to="{ name:'game1', params: {num: 123} }">  
  5.             <button>顯示</button>  
  6.         </router-link>  
  7.         <router-view></router-view>  
  8.     </div>  
  9. </template>  

運行的結果如下圖




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