在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
前言: 有时候在路由中,主要的部分是相同的,但是下面可能是不同的。比如访问首页,里面有新闻类的 项目结构如下: 我们创建了3个组件,分别是 Home.vue <template> <div class="home"> <h1>Home</h1> <router-link to="/home/news">新闻类</router-link> // 注意这里一定要写完整路径不能只写/news,需要加上/home <router-link to="/home/message">信息类</router-link> <router-view></router-view> </div> </template> <script> export default { name: "Home", }; </script> <style scoped> </style> HomeNews <template> <div class="homeNews"> <ul> <li>新闻1</li> <li>新闻2</li> <li>新闻3</li> <li>新闻4</li> </ul> </div> </template> <script> export default { name: "HomeNews" } </script> <style scoped> </style> HomeMessage <template> <div class="homeMessage"> <ul> <li>消息1</li> <li>消息2</li> <li>消息3</li> <li>消息4</li> </ul> </div> </template> <script> export default { name: "HomeMessage" } </script> <style scoped> </style> 组件写完以后,我们在 import Vue from "vue"; import VueRouter from "vue-router"; Vue.use(VueRouter); // 这里还是使用路由懒加载 const Home = () => import('../views/Home') const HomeNews = () => import('../views/HomeNews') const HomeMessage = () => import('../views/HomeMessage') const routes = [ { path: "/home", name: "Home", component: Home, // 子路由的写法 children: [ { path: "news", name: "HomeNews", component: HomeNews }, { path: "message", name: "HomeMessage", component: HomeMessage }, ] }, { path: "", redirect: "home" } ]; const router = new VueRouter({ routes, mode: 'history', }); export default router; 嵌套路由的写法很简单,你会发现, 此时,基于上面的配置,当你访问 这是因为没有匹配到合适的子路由。如果想要渲染点什么,可以提供一个 空的 子路由: const routes = [ { path: "/home", name: "Home", component: Home, children: [ { path: "news", name: "HomeNews", component: HomeNews }, { path: "message", name: "HomeMessage", component: HomeMessage }, // 新增空的子路由 { path: "", redirect: "news" } ] }, { path: "", redirect: "home" } ]; 这样页面就默认会重定向到 到此这篇关于vue.js Router嵌套路由的文章就介绍到这了,更多相关vue 嵌套路由内容请搜索极客世界以前的文章或继续浏览下面的相关文章希望大家以后多多支持极客世界! |
请发表评论