Home > Mobile >  How to re-arrange array position coming from API in Vuejs?
How to re-arrange array position coming from API in Vuejs?

Time:10-29

props: {
    groups: Array,
  },
  computed: {
    groups: function(arr) {
      alert('hi')
    }
  },
  
<div v-for="(item, index) in groups" :key="item.id" :id="item.id" class="group-name" @click="isOnlySelected ? null : $emit('setSelectedItem', item.id)">
</div>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

How to re-arrange array position coming from API in frontend?

I am able to display all the value from api to frontend. But i need to add some condition like to sort the array value. example( i need to change the array[6] position to array[1] position.

CodePudding user response:

one option would be using a computed property that sorts/swaps your array. Then, you use that computed property in your v-for.

computed: {
  rearrangeDataset () {
    if (Array.isArray(this.dataset) && this.dataset.length) {
      // Do your sorting or swapping. Always return a value in a computed property.
      let tmp = this.dataset[2]
      this.dataset[2] = this.dataset[0]
      this.dataset[0] = tmp
      return this.dataset
    } else {
      return []
    }
  }
}

Then use this prop in your v-for:

<div v-for="(item, index) in rearrangeDataset" :key="item.id" :id="item.id" class="group-name" @click="isOnlySelected ? null : $emit('setSelectedItem', item.id)">
</div>

I see that you use this dataset in a handler (its ID), so I think it is best to mutate your dataset in a computed property and return that same dataset.

I've created an example at codepen for you: https://codepen.io/LucasFer/pen/oNewOwv

Notice that you could also approach this with watch.

  • Related