@aLeXxX_03

Как отсортировать массив элементов?

Делаю страницу со списком элементов, а так же с разбивкой элементов на страницы(пагинация), но не удается сделать сортировку, т.к. сортируются элементы ТОЛЬКО на первой странице, а нужно же отсортировать ВЕСЬ массив элементов, т.е., чтобы сортировка продолжалась и после перелистывания страницы.

Как это сделать?

разметка
spoiler
<template>
  <div class="block">
    <div
      v-for="(item, index) in sort[currentPage]"
      class="item_description"
      :key="index"
    >
      <img class="salad" :src="item.image" height="200" width="305" />
      <div class="double">
        <p class="quantity">{{ item.quantity }}</p>
        <p class="priceLow">{{ item.price }}</p>
      </div>
      <p class="name" v-on:click="boolvalue">
        {{ item.name }}
      </p>
      <p class="price">{{ item.price }}</p>
    </div>

    <div class="flipping">
      <button class="btn_primary_Prev" v-on:click="prevPage">
        {{ "<" }}
      </button>
      <div class="pagination" v-for="item in bread[0].length / 6 - 1">
        <a v-on:click="countries(item)">{{ item }}</a>
      </div>
      <button class="btn_primary_Next" v-on:click="nextPage">
        {{ ">" }}
      </button>
    </div>
  </div>
</template>


JS
spoiler
<script>
import bread from "../JSON/Bread.js";

function division(arr, chunkSize) {
  const res = [];
  while (arr.length > 0) {
    const chunk = arr.splice(0, chunkSize);
    res.push(chunk);
  }
  return res;
}
const f = [...bread[0]];
const arrX = division(f, 6);

export default {
  props: {
    selected: String,
  },
  data() {
    return {
      bread,
      arrX,
      currentPage: 0,
    };
  },
  methods: {
    countries(item) {
      this.currentPage = item;
    },
    nextPage(currentPage) {
      if (this.currentPage < bread[0].length / 6 - 1)
        this.currentPage = this.currentPage + 1;
    },
    prevPage(currentPage) {
      if (this.currentPage > 0) this.currentPage = this.currentPage - 1;
    },
    changeMinus(a, b) {
      if (Number(a.price) > Number(b.price)) return 1;
      if (Number(a.price) == Number(b.price)) return 0;
      if (Number(a.price) < Number(b.price)) return -1;
    },

    changePlus(a, b) {
      if (Number(a.price) > Number(b.price)) return -1;
      if (Number(a.price) == Number(b.price)) return 0;
      if (Number(a.price) < Number(b.price)) return 1;
    },
    changePopular(a, b) {
      if (Number(a.price) > Number(b.price)) return 1;
      if (Number(a.price) == Number(b.price)) return 0;
      if (Number(a.price) < Number(b.price)) return -1;
    },
    changeDiscussed(a, b) {
      if (Number(a.price) > Number(b.price)) return -1;
      if (Number(a.price) == Number(b.price)) return 0;
      if (Number(a.price) < Number(b.price)) return 1;
    },
    changeBest(a, b) {
      if (Number(a.price) > Number(b.price)) return -1;
      if (Number(a.price) == Number(b.price)) return 1;
      if (Number(a.price) < Number(b.price)) return 0;
    },
  },
  computed: {
    sort() {
      if (this.selected === "По популярности") {
        for (let i = 0; i < this.bread.length; i++) {
          arrX[i].sort(this.changePopular);
          return arrX;
        }
      } else if (this.selected === "По возрастанию цены") {
        for (let i = 0; i < this.bread.length; i++) {
          arrX[i].sort(this.changePlus);
          return arrX;
        }
      } else if (this.selected === "По уменьшению цены") {
        for (let i = 0; i < this.bread.length; i++) {
          arrX[i].sort(this.changeMinus);
          return arrX;
        }
      } else if (this.selected === "Сначала обсуждаемые") {
        for (let i = 0; i < this.bread.length; i++) {
          arrX[i].sort(this.changeDiscussed);
          return arrX;
        }
      } else if (this.selected === "Сначала с лучшей оценкой") {
        for (let i = 0; i < this.bread.length; i++) {
          arrX[i].sort(this.changeBest);
          return arrX;
        }
      }
    },
  },
};
</script>



scss
spoiler
<style lang="scss" scoped>
.block {
  position: relative;
  left: 100px;
  display: grid;
  grid-template-columns: 350px 350px 350px;
}
.item_description {
  height: 406px;
  width: 304px;
  border: 1px solid #dadada;
  border-radius: 20px;
  margin-right: 15px;
  margin-bottom: 15px;
  padding: 10px;
  .double {
    margin-top: 15px;
    display: flex;
    justify-content: space-between;
  }
  .quantity {
    font-family: "Nunito-Medium";
    font-style: normal;
    font-weight: 400;
    font-size: 14px;
    line-height: 19px;
    color: #434343;
    margin-bottom: 45px;
  }
  .priceLow {
    font-family: "Nunito-Medium";
    font-style: normal;
    font-weight: 400;
    font-size: 14px;
    line-height: 19px;
    text-align: right;
    color: #434343;
  }
  .name {
    margin-top: -20px;
    font-family: "Nunito-Medium";
    font-style: normal;
    font-weight: 600;
    font-size: 20px;
    line-height: 27px;
    color: #000000;
    &:hover {
      cursor: pointer;
      color: red;
    }
  }
}
.flipping {
  display: flex;
  a {
    list-style: none;
    margin: 0 10px;
    cursor: pointer;
    position: relative;
    top: 5px;
  }
}

.btn_primary_Prev {
  cursor: pointer;
  width: 50px;
  height: 40px;
  border: 0;
  border-radius: 15px;
  background-color: #dcdcdc;
  font-size: 20px;
}

.btn_primary_Next {
  cursor: pointer;
  width: 50px;
  height: 40px;
  border: 0;
  border-radius: 15px;
  background-color: #dcdcdc;
  font-size: 20px;
}
</style>


Я вижу проблему в том, что сортируется НЕ исходный массив, а массив arrX.
Нужно же отсортировать массив bread, но как это сделать сохранив вывод по 6 элементов на страницу, для чего и был предназначен массив arrX?
  • Вопрос задан
  • 156 просмотров
Решения вопроса 1
Aetae
@Aetae Куратор тега Vue.js
Тлен
Чтоб сортировать весь массив - надо сортировать весь массив.
v-for="(item, index) in currentPageSortedList"
data: {
  list: [...bread[0]], // или просто bread? х.з. не ясно, что там
  // ...
},
computed: {
  sortedList() {
    const sort = {
      "По популярности": "changePopular",
      "По возрастанию цены": "changePlus",
      "По уменьшению цены": "changeMinus",
      "Сначала обсуждаемые": "changeDiscussed",
      "Сначала с лучшей оценкой": "changeBest"
    }[this.selected];
    // лишний slice здесь для того чтобы клонировать массив
    // т.к. sort мутирует исходный  
    return sort ? this.list.slice().sort(this[sort]) : this.list;    
  },
  currentPageSortedList() {
    const perPage = 6;
    const position = this.currentPage * perPage;   
    
    return this.sortedList.slice(position, position + perPage);;
  },
  // ...
},
watch: {
  // при смене выбора скидываем на первую страницу
  selected() {
    this.currentPage = 0;
  }
}
Ответ написан
Пригласить эксперта
Ответы на вопрос 1
i229194964
@i229194964
Веб разработчик
надо в вашем блоке computed уберите возвраты arrX изнутри каждой условной конструкции
computed: {
  sort() {
    if (this.selected === "По популярности") {
      for (let i = 0; i < this.bread.length; i++) {
        arrX[i].sort(this.changePopular);
      }
    } else if (this.selected === "По возрастанию цены") {
      for (let i = 0; i < this.bread.length; i++) {
        arrX[i].sort(this.changePlus);
      }
    } else if (this.selected === "По уменьшению цены") {
      for (let i = 0; i < this.bread.length; i++) {
        arrX[i].sort(this.changeMinus);
      }
    } else if (this.selected === "Сначала обсуждаемые") {
      for (let i = 0; i < this.bread.length; i++) {
        arrX[i].sort(this.changeDiscussed);
      }
    } else if (this.selected === "Сначала с лучшей оценкой") {
      for (let i = 0; i < this.bread.length; i++) {
        arrX[i].sort(this.changeBest);
      }
    }
    return arrX; // Возврат массива после всех итераций
  },
},
Ответ написан
Ваш ответ на вопрос

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

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