[Vuejs]-How to unshift object to first chunk and move oldest to new chunk in javascript?

0๐Ÿ‘

โœ…

So this is a case where it makes sense to separate your data from your view layer. It makes it easier to deal with updates if you have a single source of truth that you update, instead of trying to update your chunks directly.

So, when you get an update, unshift it into this.flights.data instead of a chunk, then make vue recalculate your chunks. This keeps your original data array as your single source of truth, and you update the chunks from it each time for your view.

๐Ÿ‘คfrodo2975

0๐Ÿ‘

Oh, I see that frodo2975 caught that you were unshifting into a computed value rather than into your data. I didnโ€™t notice that. This works as you intend:

new Vue({
  el: '#app',
  data: {
    flights: [
      7, 6, 5, 4, 3, 2, 1, 0
    ]
  },
  computed: {
    chunkedFlights() {
      return _.chunk(this.flights, 4);
    }
  },
  mounted() {
    setTimeout(() => {
      this.flights.unshift(8);
    }, 2000);
  }
});
#app {
  display: grid;
  grid-gap: 2rem;
  background-color: black;
  padding: 0.6rem;
}

.page {
  background-color: #ffe;
  padding: 0.6rem;
  grid-gap: 0.2rem;
  display: grid;
}

.row {
  background-color: blue;
  color: white;
  padding: 0.6rem;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <div v-for="chunk in chunkedFlights" class="page">
    <div v-for="flight in chunk" class="row">
      {{flight}}
    </div>
  </div>
</div>
๐Ÿ‘คRoy J

Leave a comment