R
R
Redrik_Shuhart2019-05-17 13:11:10
Vue.js
Redrik_Shuhart, 2019-05-17 13:11:10

Why are counters not sorted?

Why are running counter components not participating in sorting and how to fix it?

Example on CodePen

<div id="app">
    <table>
        <thead>
        <tr>
            <th>Counter</th>
            <th>Name</th>
        </tr>
        </thead>
        <tbody>
        <tr
                v-for="item in sortedItems"
                :key="item.id"

        >
            <td>
                {{item.counter}} <br>
                <my-counter :init_counter="item.counter"></my-counter>
            </td>
            <td>{{item.name}}</td>
        </tr>
        </tbody>
    </table>
    <button @click="changeSortDirection()">Change sort direction</button>
</div>


Vue.component('my-counter', {

    props: ['init_counter'],
    data() {
      return {
        interval: 0,
        counter: this.init_counter,
      }
    },

    mounted() {

      this.interval = setInterval(() => {
        if (this.counter < 0) {
          clearInterval(this.interval);
          return;
        } else {
          this.counter -= 1
        }
      }, 1000)
    },

    template: '<div><span style="color:red">{{ counter }}</span></div>',

  })

  const app = new Vue({
    el: '#app',
    data: {
      items: [
        {
          counter: 3000,
          name: 'Korben Dallas'
        },
        {
          counter: 5000,
          name: 'Jean-Baptiste Emmanuel Zorg'
        },
        {
          counter: 15000,
          name: 'Ruby Rhod'
        },

      ],
      sortBy: 'counter',
      sortASC: true

    },
    computed: {
      sortedItems() {
        const items = [...this.items].sort((a, b) => {
          if (a[this.sortBy] > b[this.sortBy]) {
            return 1
          }
          if (a[this.sortBy] < b[this.sortBy]) {
            return -1
          }
          return 0
        })

        if (!this.sortASC) {
          items.reverse()
        }

        return items

      }
    },

    methods: {
      changeSortDirection() {
        this.sortASC = !this.sortASC
      },
    },
  })

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2019-05-17
@Redrik_Shuhart

missing key. You seem to have specified it, but in fact there are no id in the elements of the items array. We must add.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question