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

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

 

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

  例如:在routerChildren.vue中有两个按钮,点击按钮1跳转的one页面 ,点击按钮2跳转的two页面 ,可是须要保存这两个按钮(若是直接经过this.$router.push(),按钮将会消失,会彻底跳转)vue

  1.首先咱们须要配置一下路由 ,在router.js中    vue-router

复制代码
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,
            }
        ]
    }
复制代码

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

复制代码
<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>
复制代码

在这里咱们必定要注意须要在这个组件中带上  <router-view></router-view>这个标签app

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

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

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

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

    因此说若是app下面有个One组件,可是在One组件里想要经过跳转来显示OneOne及OneTwo组件,你就必须在One组件里写一个<router-view/>。code

    ok,结束!!

相关文章
相关标签/搜索