在特定元素后追加动态vue组件 [英] Append dynamic vue component after specific element
问题描述
我想基于点击其他元素在随机位置添加组件(实际上不是随机的,基于某些逻辑)。
I want to add component in random position (not random actually, based on some logic) based on click of other elements.
在jQuery中,我们可以实现通过 $('#someId')。append('element')
或 $('#someId')。find('。someClass' ).after('element')
In jQuery, we can achieve that by $('#someId').append('element')
or by $('#someId').find('.someClass').after('element')
我想要实现的目标(jquery版本): jsfiddle
What I want achieve (jquery version): jsfiddle
如何在 Vue 中执行此操作?
注意:这不能通过 v-for
来实现,因为所有元素都不会按顺序出现或出现在同一个元素中地点。此外,组件不应出现在初始化中,因为这是动态的。
N.B: This couldn't be achieved by v-for
as all elements won't appear sequentially or in the same place. Also, components should not be appeared on initialization as this is dynamic.
推荐答案
如果这是关于安排在哪个组件出现之后另一个。假设我将所有这些组件放在一个数组中,您可以将这些组件重新排列为逻辑,并且您可以使用特殊属性:是来呈现这些组件。
If this is about arranging that which component will appear after another. Let me assume I have all those components in an array and you can re-arrange those in the array as par your logic, and you can use special attribute: is to render those component.
这里的示例我有一个组件数组,我使用 v-for
一个接一个地渲染:
Here in sample I have an array of components and I use v-for
to render those one after another:
请参阅小提琴这里。
HTML:
<div id="app">
<h1>
Following are the components
</h1>
<div v-for="comp in compArray" :is="comp"></div>
<br>
<button @click="resuffle">
Resuffle
</button>
</div>
<template id="comp1">
<div>
<span>This is component 1</span>
</div>
</template>
<template id="comp2">
<div>
<span>This is component 2</span>
</div>
</template>
<template id="comp3">
<div>
<span>This is component 3</span>
</div>
</template>
JS:
Vue.component('comp1', {
template: '#comp1',
})
Vue.component('comp2', {
template: '#comp2',
})
Vue.component('comp3', {
template: '#comp3',
})
new Vue({
el: '#app',
data: {
compArray: ['comp1', 'comp2', 'comp3']
},
methods: {
resuffle: function() {
this.compArray.push(this.compArray[1])
this.compArray.splice(1,1)
}
},
})
这篇关于在特定元素后追加动态vue组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!