在嵌套路由中,父路由向子路由傳值除了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 }) home.vue 在home中具體的值就跟在路徑后面,如 “/home/game/123”,也就是說傳遞給子路由的值就是 123
<template> <div> <h3>首頁</h3> <router-link to="/home/game/123"> <button>顯示</button> </router-link> <router-view></router-view> </div> </template>
game.vue 在子路由中,通過 this.$route.params.參數名來接受傳遞過來的值
<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> 運行的結果如下圖

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。
新聞熱點
疑難解答