Append dynamic vue component after specific element

夙愿已清 提交于 2019-12-11 03:49:20

问题


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.


回答1:


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)
    }
  },
})



回答2:


Can you provide an example of your parent component when you are traversing your array/list to map your element with a component? (just to understand your use case)

You could use v-for but on multiple arrays generated by some computed properties in the place you want to display them (if the places you wanna display components are not also randomly chosen).



来源:https://stackoverflow.com/questions/41428266/append-dynamic-vue-component-after-specific-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!