在Vite中使用Vue 3,你可以使用import.meta.glob
来导入目录下的多个Vue组件,并自动生成路由。以下是一个简单的例子:
router/index.js
// router/index.js
import { createRouter, createWebHistory } from 'vue-router';// 自动导入views目录下的所有.vue文件
const modules = import.meta.glob('/src/views/*.vue');const routes = Object.keys(modules).map((path) => {const componentName = path.split('/').pop().split('.')[0];return {path: `/${componentName=='HomeView'?'/':componentName}`,component: modules[`${path}`].default || modules[`${path}`],};
});const router = createRouter({history: createWebHistory(import.meta.env.BASE_URL),routes,
});export default router;
App.vue
<script setup>
import { RouterLink, RouterView } from 'vue-router'
import HelloWorld from './components/HelloWorld.vue'
</script><template><header><img alt="Vue logo" class="logo" src="@/assets/logo.svg" width="125" height="125" /><div class="wrapper"><HelloWorld msg="You did it!" /><nav><RouterLink to="/">Home</RouterLink><RouterLink to="/AboutView">About</RouterLink></nav></div></header><RouterView />
</template><style scoped>
header {line-height: 1.5;max-height: 100vh;
}.logo {display: block;margin: 0 auto 2rem;
}nav {width: 100%;font-size: 12px;text-align: center;margin-top: 2rem;
}nav a.router-link-exact-active {color: var(--color-text);
}nav a.router-link-exact-active:hover {background-color: transparent;
}nav a {display: inline-block;padding: 0 1rem;border-left: 1px solid var(--color-border);
}nav a:first-of-type {border: 0;
}@media (min-width: 1024px) {header {display: flex;place-items: center;padding-right: calc(var(--section-gap) / 2);}.logo {margin: 0 2rem 0 0;}header .wrapper {display: flex;place-items: flex-start;flex-wrap: wrap;}nav {text-align: left;margin-left: -1rem;font-size: 1rem;padding: 1rem 0;margin-top: 1rem;}
}
</style>
在上面的代码中,import.meta.glob
用于获取/src/views/
目录下所有的.vue
文件。然后,我们遍历这些模块,通过它们的路径生成路由。这样,你只需要将组件放入views
目录,无需手动向路由器添加每个组件。