在特定元素之后附加动态 vue 组件 [英] Append dynamic vue component after specific element

查看:32
本文介绍了在特定元素之后附加动态 vue 组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想根据点击其他元素在随机位置添加组件(实际上不是随机的,基于某些逻辑).

在 jQuery 中,我们可以通过 $('#someId').append('element')$('#someId').find('.someClass').after('元素')

我想要实现的(jquery 版本):jsfiddle

如何在 Vue 中做到这一点?

注意:这不能通过 v-for 实现,因为所有元素不会按顺序出现或出现在同一个位置.此外,组件不应出现在初始化时,因为这是动态的.

解决方案

如果这是关于安排哪个组件将依次出现.让我假设我将所有这些组件都放在一个数组中,您可以按照您的逻辑重新排列数组中的这些组件,并且您可以使用特殊属性: 来渲染那些组件.

在示例中,我有一组组件,我使用 v-for 一个接一个地渲染它们:

参见小提琴这里.

HTML:

<div id="app"><h1>以下是组件</h1><div v-for="compArray 中的comp" :is="comp"></div><br><按钮@click="resuffle">重新洗牌</按钮></div><模板 id="comp1">

<span>这是组件 1</span></div></模板><模板id="comp2">

<span>这是组件 2</span></div></模板><模板 id="comp3">

<span>这是组件 3</span></div></模板>

JS:

Vue.component('comp1', {模板:'#comp1',})Vue.component('comp2', {模板:'#comp2',})Vue.component('comp3', {模板:'#comp3',})新的 Vue({埃尔:'#app',数据: {compArray: ['comp1', 'comp2', 'comp3']},方法: {重新洗牌:函数(){this.compArray.push(this.compArray[1])this.compArray.splice(1,1)}},})

I want to add component in random position (not random actually, based on some logic) based on click of other elements.

In jQuery, we can achieve that by $('#someId').append('element') or by $('#someId').find('.someClass').after('element')

What I want achieve (jquery version): jsfiddle

How to do that in Vue?

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.

Here in sample I have an array of components and I use v-for to render those one after another:

See fiddle here.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆