2016-12-09 91 views
2

我有一个对象列表。每个对象都包含一个type字段,用于确定需要呈现的组件。例如,对于paragraph类型,我需要渲染一个名为Paragraph的组件。我大概有一打这些不同的组件类型。在Vue中渲染不同组件类型的列表

目前我在Javascript中循环访问列表。我创建一个带有随机ID的div,并用我使用new [ComponentType]({ el: ... })手动创建的Vue组件替换它。但是,这需要DOM操作。有没有更好的方法,不需要手动操纵DOM结构? v-for或同类?

+1

[v-for](https://vuejs.org/v2/guide/list.html#v-for)+ [v-is](https://vuejs.org/v2/guide /components.html#DOM-Template-Parsing-Caveats)? – joaumg

回答

1

是的,还有更好的方法。使用Dynamic Components

下面是这些文档中显示的示例。

var vm = new Vue({ 
    el: '#example', 
    data: { 
    currentView: 'home' 
    }, 
    components: { 
    home: { /* ... */ }, 
    posts: { /* ... */ }, 
    archive: { /* ... */ } 
    } 
})  

<component v-bind:is="currentView"> 
    <!-- component changes when vm.currentView changes! --> 
</component>  
+0

我会在Stackoverflow警察通过之前添加一个快速代码示例,并删除您的答案。 –