关于Vue3的嵌套路由

  • 如果在路由视图中展示的组件包含自己的路由占位符(路由出口),则此处会用到嵌套路由;
  • 如图所示:点击关于链接,则会展示About组件,在其组件中又包含了路由链接和路由占位符;

 

  • 路由嵌套规则
    • 某一个路由规则中采用 children 来声明嵌套路由的规则;
    • 嵌套路由规则中的 path 不能以 / 开头,访问需要使用过 /fatherPath/sonPath 的形式;

 

使用详解:

  • 首先下载vue-router,并且挂载,这里不细说,百度一堆
  • 我们需要一个主页面,放置router-view,作为展示页面
  • 然后需要几个子页面,放在主页面中的router-view展示

 主页面:App.vue

<template>
  <div id="app">
    <router-view></router-view>
   <router-link :to="{name:'H1'}">H1页面</router-link>
   <router-link :to="{name:'H2'}">H2页面</router-link>
  </div>
</template>
。

 这里是主页面,子页面要展示的内容都会在router-view标签内展示,router-link标签是操控router-view中显示页面的路由,:to就是点击展示的意思,这里可以展示name为H1,H2的三个路由名称对应的页面

  • 默认展示页面
<template>
  <div class="hello">
    <img src="./assets/logo.png">
    <h1>{{ msg }}</h1>
    <router-view></router-view>
    <div>
    </div>
  </div>
</template>
<script>
export default {
  name: 'HelloWorld',
  data () {
    return {
      msg: 'Welcome to Your Vue.js App'
    }
  }
}
</script>

 这个页面我们作为默认展示页面,这个页面会被展示再App.vue的router-view里面,我们的子页面会展示再这个页面的router-view里面

  • 点击展示的H1,H2
//h1
<template>
    <div class="hellow">
        <h1>{{msg}}</h1>
    </div>
</template>
<script>
export default {
  data() {
    return {
      msg:'我是h1'
    }
  },
}
</script>
//h2
<template>
    <div class="hellow">
      	<h1>{{msg}}</h1>
    </div>
</template>
<script>
export default {
  data() {
    return {
      msg:'我是h2'
    }
  },
}
</script>

这就是两个普通的展示页面,对等于你项目中要展示的内容

重点,配置路由文件 

 

 routes: [
    {
      path: '/',
      name: 'HelloWorld',
      component: HelloWorld,
      children:[{
        path:'h1',
        name:'H1',
        component:H1
      },{
        path:'h2',
        name:'H2',
        component:H2
      },
    ]
    }
  ]

首先当路径为/时候,展示我们的默认展示页面Helloworld,然后这里注意了,这里写了一个children,说明这里面的的都是Helloworld页面的子路由,这些页面将来会展示在HelloWorld页面中的router-view中,所以一个页面中的router-view是用来展示这个页面路由下面的子路由的,

总结:

嵌套路由整体来说分为几个核心:

  • 路由配置页面,设置默认路由,然后你想在哪个页面写嵌套路由,就在这个路由中写子路由

  • 子路由跳转及其展示,router-link,帮助我们操作要在router-view中展示的子路由页面

  • 8
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值