Vue3嵌套路由视图中v-for列表不渲染问题求助(Vue Router4、Vuetify)
Vue路由组件v-for列表未渲染问题解决
问题背景
通过Tabs切换路由渲染视图时,reports组件内的v-for子导航列表仅显示表头,循环内容不渲染,控制台无报错。采用CDN开发模式,所有代码在同一作用域,数据保留在父Vue实例中,疑似props传递方式错误导致数据未到达子组件。
代码片段(简化后)
app.js
const reports = { props: ['reports'], template: `<v-container> <v-row> <v-col cols="12" md="2" > <v-sheet rounded="lg" min-height="268" > <v-list density="compact"> <v-list-subheader>Reports</v-list-subheader> <v-list-item v-for="(item, i) in reports" :key="i" :value="item" color="primary" > <template v-slot:prepend> <v-icon >{{item.icon}}</v-icon> </template> <v-list-item-title >{{item.text}}</v-list-item-title> </v-list-item> </v-list> </v-sheet> </v-col> </v-row> </v-container>`, children: [], }; const routes = [ { path: "/", component: home }, { path: "/reports", props: true, component: reports, }, { path: "/schedule", props: true, component: schedule }, ]; const app = Vue.createApp({ data() { return { reports: [ { text: "My Training Status", icon: "mdi-star" }, { text: "My Team", icon: "mdi-account-multiple" }, // ...其余数据项 ], schedule: [ { text: "Schedule", icon: "mdi-calendar-month" }, { text: "My Schedule", icon: "mdi-calendar-account" }, // ...其余数据项 ], }; }, });
index.html
<div id="app"> <v-app id="inspire"> <v-app-bar class="px-3" density="compact" > <v-tabs centered color="grey-darken-2"> <v-tab to="/">Home</v-tab> <v-tab to="/reports">Reports</v-tab> <v-tab to="/schedule">Schedule</v-tab> </v-tabs> </v-app-bar> <v-main class="bg-grey-lighten-3"> <router-view></router-view> </v-main> </v-app> </div>
问题原因
路由配置中props: true的作用是将路由参数(如/reports/:id中的id)映射为组件props,但你的数据存储在父App实例的data中,这种方式无法让路由组件获取到父实例的数据,导致reports组件的reportsprops值为undefined,v-for循环没有可遍历的内容。
解决方案
方案1:通过路由props函数传递父实例数据
修改路由配置,将props设为函数,直接从父实例中获取数据:
// 先创建app实例,再定义路由 const app = Vue.createApp({ data() { return { reports: [...], schedule: [...] }; }, }); const routes = [ { path: "/", component: home }, { path: "/reports", props: () => ({ reports: app._instance.data.reports }), component: reports, }, { path: "/schedule", props: () => ({ schedule: app._instance.data.schedule }), component: schedule }, ]; // 注册路由并挂载应用 const router = VueRouter.createRouter({ history: VueRouter.createWebHashHistory(), routes, }); app.use(router); app.mount('#app');
注意:需确保路由定义在app实例创建之后,且挂载应用后app._instance才会存在。
方案2:组件内直接通过$root访问父实例数据
无需修改props,直接在组件模板中使用$root访问父实例的data:
<!-- 修改reports组件的v-for部分 --> <v-list-item v-for="(item, i) in $root.reports" :key="i" :value="item" color="primary" > <!-- 其余内容不变 --> </v-list-item>
同理,schedule组件中替换为$root.schedule即可。这种方式更适合CDN单实例的简单场景。
必补步骤:注册VueRouter
代码中缺少路由注册逻辑,需补充:
// 确保已通过CDN引入VueRouter const router = VueRouter.createRouter({ history: VueRouter.createWebHashHistory(), routes, }); app.use(router); app.mount('#app');
内容的提问来源于stack exchange,提问作者peidj
相关产品推荐
相关产品推荐

