vue-router学习4:嵌套路由

一些应用程序的 UI 由多层嵌套的组件组成。在这种情况下,URL 的片段通常对应于特定的嵌套组件结构。

定义子路由组件 

首先,你需要为嵌套路由创建对应的子组件。这些组件将在父路由组件的 <router-view></router-view> 中被渲染。

<!-- ChildComponent.vue -->  
<template>  
  <div>  
    <!-- 子组件的内容 -->  
    <p>This is a child component.</p>  
  </div>  
</template>  
  
<script lang="ts">  
import { defineComponent } from 'vue';  
  
export default defineComponent({  
  // ...  
});  
</script>

配置嵌套路由

 在路由配置文件中,你需要为父路由指定 children 属性,它是一个包含子路由定义的数组。子路由的 path 不需要以斜杠 / 开头,因为它们会被视为相对于父路由的路径。

// router/index.ts  
import { createRouter, createWebHistory } from 'vue-router';  
import ParentComponent from '../views/ParentComponent.vue';  
import ChildComponent from '../views/ChildComponent.vue';  
  
const routes = [  
  {  
    path: '/parent',  
    name: 'Parent',  
    component: ParentComponent,  
    children: [  
      {  
        path: 'child', // 注意这里不以斜杠开头  
        name: 'Child',  
        component: ChildComponent  
      }  
      // 可以继续添加更多子路由...  
    ]  
  }  
  // ...其他路由配置  
];  
  
const router = createRouter({  
  history: createWebHistory(process.env.BASE_URL),  
  routes  
});  
  
export default router;

 在父组件中使用 <router-view>

在父路由组件的模板中,你需要使用 <router-view></router-view> 来指定子路由组件的渲染位置。

<!-- ParentComponent.vue -->  
<template>  
  <div>  
    <!-- 父组件的内容 -->  
    <p>This is the parent component.</p>  
    <!-- 子路由组件将在这里渲染 -->  
    <router-view></router-view>  
  </div>  
</template>  
  
<script lang="ts">  
import { defineComponent } from 'vue';  
  
export default defineComponent({  
  // ...  
});  
</script>

导航到嵌套路由 

你可以通过编程式导航(使用 router.push 方法)或声明式导航(使用 <router-link> 组件)来导航到嵌套路由。

<!-- 声明式导航 -->  
<router-link to="/parent/child">Go to Child</router-link>

或者

<script setup>
	// 编程式导航  
	import {
		useRouter
	} from 'vue-router';

	const router = useRouter();
	const goToChild = () => {
		router.push({
			name: 'Child'
		});
	};
	}
</script>

 

  • 4
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值