比如在home页面中, 我们希望通过/home/news 访问新闻 而 /home/message访问一些内容,
即:一个路径映射一个组件, 访问这两个路径也会分别渲染两个组件.
思维分析: 那么其实就是分两步走:
1.创建对应的子组件, 并且在路由映射中配置对应的子路由.
2.在组件内部使用标签
先创建 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>
news.vue
<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>
message.vue
然后我们在路由注册,注册的时候,因为他是嵌套路由 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
路由配置文件
到这里我们已经写了 news 和 message 的组件 和 路由的定义,那么接下来使用嵌套路由
使用嵌套路由其实就是 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.vue Home组件
其实Home组件就是代替了一层路由的时候App.vue 。
然后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 和 值绑定 -->
App.vue App组件
为什么App组件什么都没写就渲染了首页? 因为在路由哪自定义了默认呈现首页组件,可以去看看:
运行:
图解组件:
这张图我画的很详细了 注意颜色搭配 完美诠释 一点都不难啊
记住定义路由的时候, 带 / 的是根路劲, 不带 / 的那么就是直接在后面加,例:
初始网址: xxx.com 那么有:
带/ : /xxx/yyy
xxx.com/xxx/yyy
不带 / : yyy
xxx.com/yyy
本文来自博客园,作者:咸瑜,转载请注明原文链接:javascript:void(0)p/15137770.html