Vuejs学习笔记(三)-18.组件的嵌套路由
以下是嵌套路由设置方法
一、创建嵌套组件
比如Home下有1个新闻列表和一个消息列表。分别创建新闻组件和消息组件,这2个组件和Home组件不是父子组件关系
HomeNews.vue
1 <template> 2 <div> 3 <ul> 4 <li>新闻1</li> 5 <li>新闻2</li> 6 <li>新闻3</li> 7 <li>新闻4</li> 8 </ul> 9 </div> 10 </template> 11 12 <script> 13 export default { 14 name: "HomeNews" 15 } 16 </script> 17 18 <style scoped> 19 20 </style>
HomeMessages.vue 消息子组件
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 <template> 2 <div> 3 <ul> 4 <li>消息1</li> 5 <li>消息2</li> 6 <li>消息3</li> 7 <li>消息4</li> 8 </ul> 9 </div> 10 </template> 11 12 <script> 13 export default { 14 name: "HomeMessage" 15 } 16 </script> 17 18 <style scoped> 19 20 </style>
二、配置组件与路由的关系
router/index.js
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 import Vue from 'vue' 2 import VueRouter from 'vue-router' 3 4 // 路由的懒加载 5 const Home = () => import('../components/Home') 6 const About = () => import('../components/About') 7 const User = () => import('../components/User') 8 const HomeMessages = ()=>import('../components/HomeMessages') 9 const HomeNews = ()=>import('../components/HomeNews') 10 11 12 Vue.use(VueRouter) 13 14 const routes = [ 15 { 16 path: '', 17 redirect: '/home' 18 }, 19 { 20 path: '/home', 21 component: Home, 22 children:[ 23 { 24 path:'', 25 redirect:'news' 26 }, 27 { 28 path:'news', 29 component:HomeNews 30 }, 31 { 32 path:'messages', 33 component:HomeMessages 34 } 35 ] 36 }, 37 { 38 path: '/about', 39 component: About 40 }, 41 { 42 path: '/user/:userName1', 43 component: User 44 } 45 ] 46 47 const router = new VueRouter({ 48 routes, 49 mode:'history' 50 }) 51 52 export default router
其中:
1.新闻组件和消息组件的路由编写在Home组件的children属性内,格式的Home组件一模一样,包括默认路径也是重定向方式展示
2.嵌套路由的路径不包括上级路由的路径,比如新闻组件的路径就写 news
三、嵌套组件的展示层(view层)在被嵌套组件内部编写,使用router-link,router-view标签,并定义嵌套组件跳转的路由路径
components/Home.vue
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 <template> 2 <div> 3 <h2>我是首页</h2> 4 <router-link to="/home/news">新闻</router-link> 5 <router-link to="/home/messages">消息</router-link> 6 <router-view></router-view> 7 </div> 8 </template> 9 10 <script> 11 export default { 12 name: "Home" 13 } 14 </script> 15 16 <style scoped> 17 18 </style>
npm run dev,页面显示结果如下:
本文来自博客园,作者:kaer_invoker,转载请注明原文链接:https://www.cnblogs.com/invoker2021/p/14987566.html