vue3+ts项目,从后端拿到组件名称动态渲染到页面上

功能:在页面上有个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)!

}

 

  • 4
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值