vue3实现目录
Vue 3 实现目录的方法
使用 <router-view> 和路由配置
在 Vue 3 中,可以通过 Vue Router 实现目录结构。创建一个路由配置文件(如 router/index.js),定义路由路径和对应的组件。在 App.vue 中使用 <router-view> 作为占位符,动态渲染匹配的组件。

// router/index.js
import { createRouter, createWebHistory } from 'vue-router';
import Home from '../views/Home.vue';
import About from '../views/About.vue';
const routes = [
{ path: '/', component: Home },
{ path: '/about', component: About }
];
const router = createRouter({
history: createWebHistory(),
routes
});
export default router;
<!-- App.vue -->
<template>
<router-view />
</template>
动态生成目录
如果需要根据数据动态生成目录,可以通过 v-for 遍历数据并渲染目录项。结合路由的 router-link 实现导航。

<template>
<div>
<ul>
<li v-for="item in menuItems" :key="item.path">
<router-link :to="item.path">{{ item.name }}</router-link>
</li>
</ul>
<router-view />
</div>
</template>
<script>
export default {
data() {
return {
menuItems: [
{ path: '/', name: 'Home' },
{ path: '/about', name: 'About' }
]
};
}
};
</script>
嵌套路由实现多级目录
对于多级目录,可以使用嵌套路由。在路由配置中通过 children 定义子路由,并在父组件中嵌套 <router-view>。
// router/index.js
const routes = [
{
path: '/products',
component: Products,
children: [
{ path: 'list', component: ProductList },
{ path: 'detail/:id', component: ProductDetail }
]
}
];
<!-- Products.vue -->
<template>
<div>
<h2>Products</h2>
<router-view />
</div>
</template>
使用 <keep-alive> 缓存目录状态
如果需要保持目录组件的状态(如滚动位置或表单数据),可以用 <keep-alive> 包裹 <router-view>。
<template>
<keep-alive>
<router-view />
</keep-alive>
</template>






