功能:在页面上有个tabs,想要点击不同tab加载不同的组件
node:
模仿后台传数据:(一个简单的get)
node下 index.js
// 模拟标签页数据
const tabData = [
{ id: 1, label: '内容1', name: '内容1', comp: "ContentPresentation" },
{ id: 2, label: '内容2', name: '内容2', comp: "ContentPresentation" },
{ id: 3, label: '内容3', name: '内容3', comp: "BenchmarkDocument" },
{ id: 4, label: '内容4', name: '内容4', comp: "ContentPresentation" },
{ id: 5, label: '内容5', name: '内容5', comp: "ContentPresentation" }
];
// 处理对 /tabs 路径的 GET 请求
app.get('/btns', (req, res) => {
// 返回模拟数据
res.json({ data: BtnData });
});
前端vue3:
Content.vue
将数据请求过来
onMounted(() => {
http.get('/tabs', {}, {}).then(res => {
resArray.value = res.data;
activeName.value = res.activeName
console.log("res", res)
}).catch(err => {
console.log("err", err)
})
})
页面引用:
Content.vue
<template>
<el-tabs v-model="activeName" class="demo-tabs">
<el-tab-pane v-for="item in resArray" :label="item.label" :name="item.name" :key="item.name"
@tab-click="handleClick">
<component :is="getAsyncComponent(item.comp)"></component>
</el-tab-pane>
</el-tabs>
</template>
注意: 标红的函数是关键;看下方代码。下方代码直接放在<script setup lang="ts">中就可
下方代码的绿色字体处引入路径,需要根据你自身代码的路径进行修改。注意:
最好循环数据的组件路径都在一处
Content.vue
// 创建一个映射来缓存异步组件
const asyncComponents = new Map()
// 函数用于获取或创建异步组件
function getAsyncComponent(componentName: string) {
if (!asyncComponents.has(componentName)) {
// 这里假设组件的路径遵循一定的模式,例如 '@/views/components/' + componentName + '.vue'
asyncComponents.set(componentName, defineAsyncComponent(() => import(`@/views/components/${componentName}/${componentName}.vue`)))
}
return asyncComponents.get(componentName)!
}