【问题标题】:Dynamically import components based on array item values根据数组项值动态导入组件
【发布时间】:2019-06-18 06:07:09
【问题描述】:

我有一个单页应用程序,我试图根据数组(blockCount)中存在的组件来导入和呈现组件。我在所述数组中存储了几个字符串(组件名称)。

Vue:
computed: {
    componentInstance () {
        for(var i = 0; i < this.blockCount.length; i++){
            return () => import(`@/components/${this.blockCount[i]}`)                    
        }
    }
},


Html:
<component v-for="component in blockCount" :is="componentInstance" />

所以我遇到的问题是函数在 item[0] 处停止并且只是迭代该项目。而且我不太确定如何以动态方式迭代此函数。

【问题讨论】:

    标签: vue.js components


    【解决方案1】:

    你可能想定义一个子组件

    ChildComponent.vue

    <template>
      <component :is="componentInstance" />
    </template>
    
    <script>
    export default {
      props: ['componentName'],
      computed: {
        componentInstance() {
          return () => import(`@/components/${this.componentName}`)                    
        }
      }
    }
    </script>
    

    并在父级中渲染:

    <child-component v-for="(component, index) in blockCount" :key="index" :componentName="component"/>
    

    【讨论】:

    • 这以某种方式冻结并崩溃了我的客户端。无法测试结果
    • 无,在那之前它会冻结。
    • 似乎工作正常。然而,我更倾向于有一个不需要创建子组件的解决方案。这不可能吗?
    • 一开始我觉得可以用方法,但是好像不行。不确定是否有更好的解决方案。
    猜你喜欢
    • 1970-01-01
    • 2021-07-13
    • 1970-01-01
    • 2019-09-15
    • 2019-04-23
    • 2023-03-24
    • 2016-09-09
    • 2020-06-18
    • 2019-02-03
    相关资源
    最近更新 更多