向父组件添加任意Vue.js个组件

Add arbitrary Vue.js components to parent component

我在 html5 游戏中使用 Vue.js 到 build ui。我有一个案例,我想定义 ui-containers,它基本上只是将其他 ui-components 分组并将它们定位到屏幕上的某个位置。所以我可以进行这样的事情:

<ui-container>
  <ui-component1></ui-component1>
  <ui-component2></ui-component2>
  <ui-component3></ui-component3>
</ui-container>

我需要根据表示容器内容的数据模型动态添加和删除这些组件。问题是我想保持 ui-container 通用,这样我就可以将任何 Vue 组件附加到它,而无需在模板中获得有关可能存在哪些组件的信息。

我用谷歌搜索并找到了这个涉及动态注入组件的示例:http://forum.vuejs.org/topic/349/injecting-components-to-the-dom 虽然示例中的数据驱动版本易于制作和理解,但它使用 v-for 作为标记,因此需要 res 一个来事先了解子组件的类型。

所以问题是,我如何概括该示例以动态处理任何组件?我的数据模型是否应该具有组件类型或标签名称,然后将其插入到 v-for 中?或者是否存在针对这种请求uirement 的现有机制?

您可以使用特殊的 is 属性来动态设置组件的类型。这是docs。代码看起来有点像:

<div id="app">
  <div v-for="component in components" :is="component.type" :value="component.value"></div>
</div>

工作 fiddle 一起玩:Dynamic Vue.js components