Vite中用Glob导入Vue组件为啥不生效?

子聪 Dev 阅读 12

我在用Vite的Glob导入动态加载views目录下的页面组件,但页面一片空白,控制台也没报错,是写法有问题吗?

我试过直接import单个组件是能显示的,换成Glob就不行了,是不是解构方式不对?

<script setup>
const modules = import.meta.glob('@/views/*.vue')
console.log(modules) // 能看到对象,但怎么用?
// 想在router里用,但这里先简单测试
</script>

<template>
  <div>测试Glob导入</div>
</template>
我来解答 赞 2 收藏
二维码
手机扫码查看
1 条解答
开发者宝娥
你这个写法本身没问题,但 import.meta.glob 返回的不是组件对象本身,而是一堆异步加载函数的集合,你直接打印出来能看到对象是对的,但得用对方式。

你得这样用:

<script setup>
const modules = import.meta.glob('@/views/*.vue')
// modules 是个对象,比如 { '@/views/Home.vue': () => import('@/views/Home.vue') }
// 所以你要渲染某个组件,得先取到对应函数再调用
</script>

<template>
<div>测试Glob导入</div>
</template>


如果你只是想在模板里动态渲染某个组件,比如根据路由参数加载,得这样:

<script setup>
import { ref, onMounted, shallowRef } from 'vue'

const modules = import.meta.glob('@/views/*.vue')
const currentComponent = ref(null)

onMounted(() => {
const path = '@/views/Home.vue' // 这里替换成你实际要加载的路径,比如从 route.params 拿
if (modules[path]) {
modules[path]().then((mod) => {
currentComponent.value = mod.default
})
}
})
</script>

<template>
<component v-if="currentComponent" :is="currentComponent" />
</template>


但你提到了路由里用,那更常见的是配合 vue-router 的动态导入用法,比如:

// router/index.js
const routes = [
{
path: '/home',
component: () => import.meta.glob('@/views/*.vue')['@/views/Home.vue']
}
]


或者更稳妥点,避免路径硬编码,用函数包一层:

const loadView = (path) => {
const views = import.meta.glob('@/views/*.vue')
return () => views[path]().then(m => m.default)
}

// 然后 routes 里这样用
component: loadView('@/views/Home.vue')


不过现在新版 vue-router 推荐直接用 defineAsyncComponent + import(),Glob 更适合做批量注册组件或者自动注册路由这种场景,你如果只是想加载单个页面,其实直接 import Home from '@/views/Home.vue' 反而更直观。

另外确认下你 Vite 版本是不是 4+,老版本对 import.meta.glob 支持不太一样,不过一般现在都 5 了问题不大。

最后说个容易踩的坑:路径别写成 '@/views/*.vue' 这样,Vite 默认只支持相对路径,得写成 './views/*.vue' 或者用 import.meta.glob('@/views/*.vue', { eager: true }) 显式指定路径前缀,不过 @ 别名一般不用管,只要 vite.config.js 里配置了 resolve.alias 就行。

你要是还是一片白,贴下你的路由配置或者完整代码片段我再看看。
点赞
2026-02-24 16:00