map.set-array.slice返回太多项目

时间:2019-03-30 17:17:23

标签: javascript arrays vue.js

我正在处理vue项目,并且尝试对表进行分页。
发生了一个错误,我无法弄清楚代码出了什么问题。

我在一个简化的示例中重现了该问题:https://codesandbox.io/s/rj23rqp2k4

问题在于,将设置更改为每页10个,然后又更改为每页5个,第二页上有6个项目而不是5个。

HTML:

<template>
  <div id="app">
    <button @click="currentPage-=1">Previous</button>
    <button @click="currentPage+=1">Next Page</button>
    <select v-model="perPage">
      <option value="5">5 per page</option>
      <option value="10">10 per page</option>
    </select>
    <hr>
    <ul v-for="item in pages.get(currentPage)" :key="item">
      <li>
        <strong>{{ item }}</strong>
      </li>
    </ul>
    <hr>
    <h5>Current Page: {{currentPage}}</h5>
  </div>
</template>

脚本:

<script>
export default {
  name: "App",

  data() {
    return {
      data: ["a1","b2","c3","d4","e5","f6","g7","h8","i9","j10","k11"],
      perPage: 5,
      currentPage: 1
    };
  },

  computed: {
    numberOfPages: function() {
      let x = this.data.length / this.perPage;
      if (x % 1 !== 0) {
        x = Math.floor(x) + 1;
      }
      return x;
    },
    pages: function() {
      let pgs = new Map();
      for (
        let index = 0, start = 0, end = this.perPage;
        index < this.numberOfPages;
        index++
      ) {
        pgs.set(index + 1, this.data.slice(start, end));
        start += this.perPage;
        end += this.perPage;
      }
      return pgs;
    }
  }
};
</script>

该错误似乎必须在页面功能中,因为一页上有6个项目,而事实并非如此。

2 个答案:

答案 0 :(得分:2)

通过下拉列表更改值perPage后,它不再起作用的原因是,perPage的值变成了string而不是number

要使其正常工作,请像下面的示例一样在使用它之前先将this.perPage的值转换为number

pages: function() {
  let pgs = new Map();
  const perPage = Number(this.perPage);
  for (
    let index = 0, start = 0, end = perPage;
    index < this.numberOfPages;
    index++
  ) {
    pgs.set(index + 1, this.data.slice(start, end));
    start += perPage;
    end += perPage;
  }
  return pgs;
}

您还可以调整@charliefl的解决方案以使其更整洁,但请确保也进行转换。

请参见working implementation

答案 1 :(得分:0)

尝试仅使用start并向其添加this.perPage作为结束索引:

 pages: function() {
      let pgs = new Map();
      for (
        let index = 0, start = 0 ;
        index < this.numberOfPages;
        index++
      ) {
        pgs.set(index + 1, this.data.slice(start, start + this.perPage));
        start += this.perPage;           
      }
      return pgs;
    }