首页 > 解决方案 > 通过名称和属性盲动态加载 vuejs 组件

问题描述

我想在 vuejs CLI 中将组件动态加载为单个文件组件,在 ajax 请求之前,我不知道将加载哪个组件,并且在页面加载时无法加载 150 个组件。

这是 ajax 响应的示例:

[
  {is="Title", text:"Hello World"},
  {is:"Status", type:"info", text:"Look at these beautiful photos"},
  {is:"Carousel", imgs:["/img/1.jpg","/img/2.jpg","/img/3.jpg"]},
  {is:"Status", type:"alert", text:"These images are the property of the creator"},
]

我想要一个像这样呈现的 vue 组件:

<template>
  <component is="Title" text="Hello World"/>
  <component is="Status" type="info" text="Look at these beautiful photos"/>
  <component is="Carousel" imgs="['/img/1.jpg','/img/2.jpg','/img/3.jpg']"/>
  <component is="Status" type="alert", text="These images are the property of the creator"/>
</template>
<script>
    import Title from '@/components/libs/Title.vue'
    import Status from '@/components/libs/Status.vue'
    import Carousel from '@/components/libs/Carousel.vue'
    export default {
        components: {
            Title,
            Status,
            Carousel
        },
    }
</script>

标签: vue.jsvue-component

解决方案


应用程序.vue

<template>
  <div id="app">
    <DynamicComponentSet :definition="response"/>
  </div>
</template>

<script>
import DynamicComponentSet from "@/components/DynamicComponentSet";

export default {
  name: "App",
  components: {
    DynamicComponentSet
  },
  data() {
    return {
      response: [
        { is: "Title", text: "Hello World" },
        { is: "Status", type: "info", text: "Look at these beautiful photos" },
        { is: "Carousel", imgs: ["/img/1.jpg", "/img/2.jpg", "/img/3.jpg"] },
        {
          is: "Status",
          type: "alert",
          text: "These images are the property of the creator"
        }
      ]
    };
  }
};
</script>

动态组件集.vue

<template>
  <div>
    <component v-for="(comp, index) in definition" :key="index" v-bind="comp" :is="comp.is"/>
  </div>
</template>

<script>
export default {
  name: "DynamicComponentSet",
  components: {
    Title: () => import("@/components/Title.vue"),
    Status: () => import("@/components/Status.vue"),
    Carousel: () => import("@/components/Carousel.vue")
  },
  props: {
    definition: Array
  }
};
</script>

注 1:is必须在此处指定所有可能的值components。组件按需加载(异步组件)。

注意 2:所有单个response对象的属性都v-bind="comp"使用props 作为对象语法传递到单个组件中,因此数据属性名称/类型必须与每个组件的 props 匹配......

注意 3::is="comp.is"实际上不需要让它工作,因为它is是与其他道具一起传递的。我补充说只是为了让 ESLint 开心......

演示


推荐阅读