2

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.

2 Answers 2

2

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

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).

1
  • You can get details what I'm trying to achieve from here: stackoverflow.com/questions/41415523/… Anyway, this won't be an array of items. I want to show single component in different places (after the row of the clicked panel).
    – Sovon
    Commented Jan 2, 2017 at 17:27

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.