思维分析:
那么其实就是分两步走:
先创建 news 和 message 的组件:
<template>
<div>
<h1>今日新闻</h1>
<ul>
<li>新闻1</li>
<li>新闻2</li>
<li>新闻3</li>
<li>新闻4</li>
<li>新闻5</li>
</ul>
</div>
</template>
<script>
export default {
}
</script>
<style>
</style>
<template>
<div>
<h1>今日消息</h1>
<ul>
<li>消息1</li>
<li>消息2</li>
<li>消息3</li>
<li>消息4</li>
<li>消息5</li>
</ul>
</div>
</template>
<script>
export default {
}
</script>
<style>
</style>
然后我们在路由注册,注册的时候,因为他是嵌套路由 HOME嵌套 news 或 message ,所以这里要加children属性定义嵌套路由中的路由,注意看注释:
import Vue from ‘vue‘ import VueRouter from ‘vue-router‘ const home = ()=>import(‘../components/Home‘) const news = ()=>import(‘../components/news‘) const message = ()=>import(‘../components/message‘) //注册路由插件 Vue.use(VueRouter) //这里配置组件的映射和路径 【一个组件对应一个对象】 const routes = [ {path:‘/‘,component:home}, //首页默认是 Home { /* 这里配置Home路径的嵌套路由 其实就是childreb这个属性!!! */ path:"/home", component:home, children:[ //定义嵌套路由 路径 和 组件 {path:"news",component:news}, {path:"message",component:message}, ] } ] const router = new VueRouter({ routes, mode:"history", linkActiveClass:"BiHu" }) export default router

使用嵌套路由其实就是 HOME组件,因为嵌套嘛:
<template>
<div class="Home">
<p style="margin-left:100px; font-size:30px;">BiHu新闻网首页</p>
<router-link to="/home/news" >时实新闻</router-link>
----------
<router-link to="/home/message" >我的消息</router-link>
<!-- 这里为什么要放router-view 自己想想 -->
<router-view></router-view>
<hr>
</div>
</template>
<script>
export default {
name:"Home",
}
</script>
<style>
.home{
border: greenyellow solid 2px;
}
</style>
其实Home组件就是代替了一层路由的时候App.vue 。
<template> <div id="app"> <router-view></router-view> </div> </template> <script> export default { name:"App", } </script> <style> </style> <!-- <router-link to="home" tag="button" replace >Home</router-link> --> <!-- <router-link to="about" tag="button" replace >About</router-link> --> <!-- <router-link :to="‘/user/‘ + username" tag="button" replace >User</router-link> 主要是to 和 值绑定 -->
运行:


原文:https://www.cnblogs.com/bi-hu/p/15137770.html