@Redrik_Shuhart

Почему не сортируются счётчики?

Почему запущенные компоненты-счётчики не участвуют в сортировке и как это исправить?

Пример на 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
			},
		},
	})
  • Вопрос задан
  • 93 просмотра
Решения вопроса 1
0xD34F
@0xD34F Куратор тега Vue.js
Отсутствует key. Вы его вроде бы указали, но ведь реально никаких id в элементах массива items нет. Надо добавить.
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы