vue 路由嵌套 及 router-view vue-router --》children

时间:2023-03-10 08:06:14
vue 路由嵌套 及 router-view     vue-router --》children

vue 路由嵌套 vue-router --》children

在项目的很多子页面中,我们往往需要在同一个页面做一个组件的切换,同时保存这个页面的部分数据(比如树形菜单),进而显示不同的数据,之前我都是通过v-show/v-if来实现,但当切换的组件太多时,上述方法显然不太合理,而在实际开发中,当你切换的组件太多时,后端往往会将你切换组件的路由给你,所以在这说一下关于vue-router中children,来解决此问题。

  例如:在routerChildren.vue中有两个按钮,点击按钮1跳转的one页面 ,点击按钮2跳转的two页面 ,但是需要保存这两个按钮(如果直接通过this.$router.push(),按钮将会消失,会完全跳转)

  1.首先我们需要配置一下路由 ,在router.js中    

vue 路由嵌套 及 router-view     vue-router --》children
import RouterChildren from "./views/routerChildren.vue"
import RouterChildrenOne from "./views/children/one.vue"
import RouterChildrenTwo from "./views/children/two.vue" {
path: "/routerChildren",
name: "routerChildren",
component: RouterChildren,
children: [
{
path: '/', //代表 /routerChildren
name: "routerChildren",
redirect:'/routerChildren/one' //当我们访问存在子路由的页面时,重定向为第一个子路由,切记,如果写了component,那么这个component也将显示
},
{
path: '/routerChildren/one',
component: RouterChildrenOne,
},
{
path: '/routerChildren/two',
component: RouterChildrenTwo,
}
]
}
vue 路由嵌套 及 router-view     vue-router --》children

2.在rouertChildren.vue组件中,我们写一下简单的样式及跳转

vue 路由嵌套 及 router-view     vue-router --》children
<template>
<div>
<h1>
<p @click="handleOne">子路由1</p>
<p @click="handleTwo">子路由2</p>
</h1>
<router-view></router-view>
</div> </template>
<script>
export default {
methods: {
handleOne() {
this.$router.push('/routerChildren/one')
},
handleTwo() {
this.$router.push('/routerChildren/two')
}
}
}
</script>
<style scoped>
h1 {
display: flex;
justify-content: center;
}
p {
margin: 20px;
cursor: pointer;
}
</style>
vue 路由嵌套 及 router-view     vue-router --》children

在这里我们一定要注意需要在这个组件中带上  <router-view></router-view>这个标签

否则,你切换的one组件和two组件里面的内容不会显示,

  谈下个人对<router-view/>这玩意儿的理解:

    我感觉这个东西就是一个当前组件的容器,与当前组件相关联的组件想要显示,就需要通过他,也就是说一层路径对应一个<router-view/>,每一个与组件相匹配的路由都会在<router-view/>中显示

    我们的项目中所有组件都关联在app这个组件上,如何进行切换显示的呢,就是通过这个东西<router-view/>,

    所以说如果app下面有个One组件,但是在One组件里想要通过跳转来显示OneOne及OneTwo组件,你就必须在One组件里写一个<router-view/>。

  ok,结束!!