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>

运行后的结果,传递的参数在地址栏中有显示

原文地址:https://www.cnblogs.com/wzbk/p/10308213.html