Search code examples
vue.jssortingdynamiccomponentsvue-dynamic-components

How to change rendering order of the components in vueJs?


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!


Solution

  • 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>