vue2嵌套路由嵌套路由嵌套路由展示
时间: 2023-10-09 20:08:32 浏览: 52
Vue 2 的嵌套路由可以帮助我们构建复杂的页面结构。在嵌套路由中,一个路由可以包含多个子路由,而每个子路由又可以再次包含自己的子路由。
下面是一个示例,展示了如何在 Vue 2 中使用嵌套路由:
首先,我们需要设置主路由(父路由),这可以在 `router/index.js` 文件中完成:
```javascript
import Vue from 'vue'
import Router from 'vue-router'
Vue.use(Router)
export default new Router({
routes: [
{
path: '/',
component: Home,
children: [
{
path: 'about',
component: About,
children: [
{
path: 'contact',
component: Contact
},
// 其他子路由...
]
},
// 其他子路由...
]
}
]
})
```
在上面的示例中,我们定义了一个主路由 `/`,它的组件是 `Home`。然后,我们定义了一个子路由 `/about`,它的组件是 `About`。在 `About` 组件中,又定义了一个子路由 `/contact`,它的组件是 `Contact`。
现在,我们可以在 `Home` 组件的模板中添加一个 `<router-view>` 标签来展示嵌套路由的内容:
```html
<template>
<div>
<h1>Home</h1>
<router-view></router-view>
</div>
</template>
```
同样地,在 `About` 组件的模板中也要添加一个 `<router-view>` 标签:
```html
<template>
<div>
<h2>About</h2>
<router-view></router-view>
</div>
</template>
```
这样,当我们访问 `/about` 路径时,`Home` 组件会显示出来,并且在其中展示 `About` 组件。
当访问 `/about/contact` 路径时,`Home` 和 `About` 组件都会显示出来,并且在 `About` 组件中展示 `Contact` 组件。
希望这个示例对你有所帮助!如果你还有其他问题,请随时提问。