vue根据接口返回 动态渲染组件的实现方法

使用了vue中的动态组件
https://v3.cn.vuejs.org/guide/component-dynamic-async.html#%E5%8A%A8%E6%80%81%E7%BB%84%E4%BB%B6-%E5%BC%82%E6%AD%A5%E7%BB%84%E4%BB%B6

父容器

<template>
  <template v-for="item in compList" :key="item">
    <component v-bind:is="item.compKey" :compData="item.compData"/>
  </template>
</template>
<script>
import {defineComponent} from "vue";
import Header from './components/Header'
import Product from './components/Product'
import Luck from './components/Luck'
import Footer from "./components/Footer"
export default defineComponent({
  name: "Container",
  components: {
    Header,
    Product,
    Luck,
    Footer
  },
  setup() {
    /**
     * 后台返回的模块名称及数据
     * 数据:可以与模块顺序一起返回,也可返回模块id,在模块中进行调用数据
     * 可以将compKey写在前端,后台匹配 1,2,3
     */
    const compList = [
      {compKey: 'Header', compData: {title: '顶部组件'}},
      {compKey: 'Product', compData: {title: '商品组件2'}},
      {compKey: 'Product', compData: {title: '商品组件1'}},
      {compKey: 'Luck', compData: {title: '抽奖组件'}},
      {compKey: 'Footer', compData: {title: '底部组件'}}
    ]
    return {
      compList
    }
  }
})
</script>


测试组件都是基础的

Hader.vue

<template>
  <div>子组件:Header{{ compData }}</div>
</template>

<script>
import { defineComponent, getCurrentInstance } from 'vue'
export default defineComponent({
  name: "Header",
  props: {
    compData: {
      type: Object
    }
  },
  setup(){
    const {proxy} = getCurrentInstance()
    console.log(proxy)
    return {}
  }
})
</script>

<style scoped>

</style>


在这里插入图片描述

Logo

前往低代码交流专区

更多推荐