詳解vue嵌套路由-params傳遞參數(shù)
在嵌套路由中,父路由向子路由傳值除了query外,還有params,params傳值有兩種情況,一種是值在url中顯示,另外一種是值不顯示在url中。
1、顯示在url中
index.html
<div id="app"> <!-- router-view 路由出口, 路由匹配到的組件將渲染在這里 --> <router-view></router-view> </div>
main.js params傳值是通過 :[參數(shù)值] 如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 }
]
}
]
//創(chuàng)建路由實例
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.參數(shù)名來接受傳遞過來的值
<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中是要傳遞的參數(shù),這樣傳遞的參數(shù)就不會顯示在url中。
<template>
<div>
<h3>首頁</h3>
<router-link :to="{ name:'game1', params: {num: 123} }">
<button>顯示</button>
</router-link>
<router-view></router-view>
</div>
</template>
運行的結(jié)果如下圖

以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Vue3中當v-if和v-for同時使用時產(chǎn)生的問題和解決辦法
封裝一個組件時,我使用到了v-for和v-if,它們在同一標簽內(nèi),總是提示v-for循環(huán)出來的item在實例中沒有被定義,查詢資料后原因是因為v-for和v-if在同級使用時,v-if優(yōu)先級比v-for高,所以本文給大家介紹了Vue3中當v-if和v-for同時使用時產(chǎn)生的問題和解決辦法2024-07-07
vue3 onMounted異步函數(shù)同步請求async/await實現(xiàn)
這篇文章主要為大家介紹了vue3 onMounted初始化數(shù)據(jù)異步函數(shù)/同步請求async/await實現(xiàn)詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-07-07
Vue3后臺管理系統(tǒng)之創(chuàng)建和配置項目
后臺管理系統(tǒng)是我們?nèi)粘i_發(fā)學習經(jīng)常遇到的一個項目,下面這篇文章主要給大家介紹了關(guān)于Vue3后臺管理系統(tǒng)之創(chuàng)建和配置項目的相關(guān)資料,文中通過實例代碼介紹的非常詳細,需要的朋友可以參考下2022-09-09

