vue嵌套路由-query傳遞參數(三)


在嵌套路由中我們經常會遇到父路由向子路由里面傳遞參數,傳遞參數有兩種方法,通過 query 或者 params

index.html

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

main.js 同樣通過重定向來顯示父路由

 1 import Vue from 'vue'
 2 import VueRouter from 'vue-router'
 3 Vue.use(VueRouter)
 4  
 5 //引入兩個組件
 6 import home from "./home.vue"
 7 import game from "./game.vue"
 8 //定義路由
 9 const routes = [
10     { path: "/", redirect: "/home" },//重定向
11     {
12         path: "/home", component: home,
13         children: [
14             { path: "/home/game", component: game }
15         ]
16     }
17 ]
18 //創建路由實例
19 const router = new VueRouter({routes})
20  
21 new Vue({
22     el: '#app',
23     data: {
24         id:123,
25     },
26     methods: {
27  
28     },
29     router
30 })

home.vue 通過query來傳遞num參數為1,相當與在 url 地址后面拼接參數

 1 <template>
 2     <div>
 3         <h3>首頁</h3>
 4         <router-link :to="{ path:'/home/game', query: { num:  1} }">
 5             <button>顯示<tton>
 6         </router-link>
 7  
 8         <router-view></router-view>
 9     </div>
10 </template>

game.vue 子路由中通過 this.$route.query.num 來顯示傳遞過來的參數

    <template>
        <h3>王者榮耀{{ this.$route.query.num }}</h3>
    </template>

運行后的結果,傳遞的參數在地址欄中有顯示

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM