首页 > 解决方案 > 我如何为一些单独的 vue 应用程序存储一组组件?

问题描述

我正在通过 Vue.js 编写自己的项目

我有几个应用程序,其中包括一组通用组件和独特的组件。

我希望能够为这些应用程序配置配置,我可以在其中为它们指定必要的组件和数据,如下所示:

"load": [
    "Core.vue",
    "Accordion.vue",
    "Buttons.vue",
    "Table.vue",
    "etc"
],
"components": {
    "table": {
        "name": "title"
    },
    "accordion": {
        "tabs": {
            "tab1": {
                "name": 'tab1'
            },
            "tab2": {
                "name": 'tab2'
            }
        }
    }
}

然后组件获取这些数据并显示它:

<template>
  <div> {{ name }} </div>
</template>

<script>
  export default {
    name: "Table",
    props: ['name']
  }
</script>

我认为它可以是 JSON 或 .yml 文件(或任何其他格式),但我不明白如何处理它们?

标签: vue.jsvuejs2vue-component

解决方案


我认为您正在寻找动态组件。这样,您可以将所需的组件保存在某个 json 文件中,将其导入父组件并动态创建子组件,例如,如果您有一个jsonMap.json文件:

{
   landingPage:{
      banners:['child1','child2']
   }
}

然后landingPage.vue

<template>
<div>
  <component v-for="(banner,index) in getBanners" :is="banner" :key="index"</component>
   //this is a dynamic component. the 'is' attribute determine what it will be. 
</div>
</template>

<script>
import jsonMap from 'path/to/jsonMap'
import child1 from 'path/to/shared/components/child1.vue'
import child2 from 'path/to/shared/components/child2.vue'
import child3 from 'path/to/shared/components/child3.vue'

export default {

  name: 'landingPage',
  components:{child1,child2,child3},

  methods:{
    getBanners(){
      return jsonMap[this.name].banners
    }
  }
}
</script>

登陆页面将根据 jsonMap 呈现 2 个横幅。请注意,尽管您必须导入和注册您的组件,但这不能动态完成。


推荐阅读