如何在Vue.js中添加动态组件/部分 [英] How to add dynamic components/partials in Vue.js
问题描述
我需要根据用户交互动态地将子组件添加到组件中。我查看了一些旧问题,但对我来说这似乎是一个肮脏的黑客,此外,它这是一个老问题,vue开发非常活跃,所以我不知道现在是否有更好的方法。
I need to add child components dynamically to a component based on user interaction. I looked to some old issue but it seems like a dirty hack to me, besides, it is an old issue, and vue development is really active, so I don't know if there is some better approach now.
到目前为止我所尝试的是这个小提琴但显然不起作用,它说 $ mount
只能调用一次。我不知道该怎么做,我的另一个选择是动态组件,但为此我还需要动态添加一个< component>
元素,以便它变成几乎相同的问题。
What I've tried so far is here on this fiddle but is obviously not working, it says that $mount
can only be called once. I don't know how to do it, my other option would be dynamic component, but for that I would also have to add a <component>
element dynamically so it turns to be almost the same issue.
那么如何在客户点击或其他客户事件上添加组件?
So how could I add a component on client click or other client event?
推荐答案
您想从一开始就将自定义组件放在那里,并使用 v-if
或 v-for
显示,隐藏,添加或减去这些组件。您让数据驱动DOM,而不是自己管理DOM。小提琴示例: https://jsfiddle.net/f5n5z5oo/2/
You want to put the custom components there right from the start, and use v-if
or v-for
to show, hide, add, or subtract these components. You let the data drive the DOM, not managing the DOM yourself. Fiddle example: https://jsfiddle.net/f5n5z5oo/2/
您甚至可以让组件动态更改他们使用的组件类型
:
You can even make the components dynamically change what type of component they are using is
:
data: {
elements: [
{ type: 'component-a' },
{ type: 'component-b' }
]
}
<div v-for="element in elements" :is="element.type"></div>
如果您对您的用例更具体,我会尝试进一步提供帮助!
If you're more specific about your use case I will try to help further!
这篇关于如何在Vue.js中添加动态组件/部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!