轉載:https://blog.csdn.net/k491022087/article/details/70232965
在嵌套路由中,父路由向子路由傳值除了query外,還有params,params傳值有兩種情況,一種是值在url中顯示,另外一種是值不顯示在url中。
1、顯示在url中
index.html
- <div id="app">
- <!-- router-view 路由出口, 路由匹配到的組件將渲染在這裏 -->
- <router-view></router-view>
- </div>
main.js params傳值是通過 :[參數值] 如path: "/home/game/:num"
- import Vue from 'vue'
- import VueRouter from 'vue-router'
- Vue.use(VueRouter)
- //引入兩個組件
- import home from "./home.vue"
- import game from "./game.vue"
- //定義路由
- const routes = [
- { path: "/", redirect: "/home" },//重定向
- {
- path: "/home", component: home,
- children: [
- { path: "/home/game/:num", component: game }
- ]
- }
- ]
- //創建路由實例
- const router = new VueRouter({routes})
- new Vue({
- el: '#app',
- data: {
- id:123,
- },
- methods: {
- },
- router
- })
- <template>
- <div>
- <h3>首頁</h3>
- <router-link to="/home/game/123">
- <button>顯示</button>
- </router-link>
- <router-view></router-view>
- </div>
- </template>
- <template>
- <h3>王者榮耀{{ this.$route.params.num }}</h3>
- </template>
2、不顯示在url中,如果在PC端將傳遞的值顯示在url中,這樣無形中就存在安全隱患,如果客戶不小心修改了url那樣就會出錯,移動端就無所謂了,如何才能不顯示在url中,同樣很簡單,但是需要給映射的路徑起一個別名,通過name來取別名
同樣只需將上面的main.js中的定義路由改爲如下樣子,在子路由中通過name來給路徑其一個game1的別名。
- //定義路由
- const routes = [
- { path: "/", redirect: "/home" },//重定向
- {
- path: "/home", component: home,
- children: [
- { name: "game1", path: "/home/game/", component: game }
- ]
- }
- ]
home.vue 中router-link修改爲:to="{ name:'game1', params: {num: 123} }" params中是要傳遞的參數,這樣傳遞的參數就不會顯示在url中。
- <template>
- <div>
- <h3>首頁</h3>
- <router-link :to="{ name:'game1', params: {num: 123} }">
- <button>顯示</button>
- </router-link>
- <router-view></router-view>
- </div>
- </template>
運行的結果如下圖