How to change rendering order of the components in vueJs?

999 Views Asked by At

I want to reorder my child components with a data from api in my parent components. Please take a look at the example below:

Parent component:

   <div v-if="data">
    <Component_1 />
    <Component_2 />
    <Component_3 />
    <Component_4 />
  </div>

I want to render like this with a data from backend and user can be able to send me a data like wordpress to reorder the components every time that he wants:

Parent component after user change the order data from backend:

<div v-if="data">
    <Component_4 />
    <Component_2 />
    <Component_1 />
    <Component_3 />
  </div>

Do I have a way to make it done ? or It's impossible in vuejs?

I tried to make dynamics components but i can't to sort them or I don't know!

3

There are 3 best solutions below

2
Neha Soni On BEST ANSWER

You can loop on the backend response array and use the :is attribute to render the components in the array's item order.

Here is a demo-

const Component_1 = Vue.component('Component_1', {
  template: '<div>Component 1</div>'
})
const Component_2 = Vue.component('Component_2', {
  template: '<div>Component 2</div>'
})
const Component_3 = Vue.component('Component_3', {
  template: '<div>Component 3</div>'
})

new Vue({
  el: "#app",
  data() {
    return {
      response: [1, 2, 3]
    }
  },
  components: {
    Component_1,
    Component_2,
    Component_3
  },
  methods: {
    reorder() {
      // Suppose you get the data in numbers from the backend like
      // [1,2,3] or [2,3,1]
      this.response = [2, 3, 1];
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <button @click="reorder()">Re-order</button>
  <component :is="`Component_${num}`" v-for="(num, i) in response" :key="i"></component>
</div>

0
Boussadjra Brahim On

If you can order the numbers, you can use component and its prop is to render the components dynamically :

<div v-if="data">
  <template v-for="num in orderedNums">
    <component :is="`Component_${num}`"
 </template>
</div>
0
qiqqq On

When you have some array of components names in the correct order from the backend:

const componentsOrder = ['Component_4', 'Component_1', 'Component_2', 'Component_3'];

In the Vue template you can use <component> tag with is attribute:

<div v-if="data">
  <component 
    v-for="componentName in componentsOrder" 
    :key="componentName" 
    :is="componentName" 
  />
  </div>