当前位置:首页 > VUE

vue实现翻页效果

2026-01-08 04:06:44VUE

Vue实现翻页效果的方法

使用v-for和计算属性

通过计算属性动态计算当前页显示的数据,结合v-for渲染分页内容。定义currentPagepageSize控制分页逻辑。

vue实现翻页效果

<template>
  <div>
    <div v-for="item in paginatedData" :key="item.id">{{ item.name }}</div>
    <button @click="prevPage">上一页</button>
    <span>{{ currentPage }} / {{ totalPages }}</span>
    <button @click="nextPage">下一页</button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      dataList: [...], // 原始数据
      currentPage: 1,
      pageSize: 10
    };
  },
  computed: {
    paginatedData() {
      const start = (this.currentPage - 1) * this.pageSize;
      const end = start + this.pageSize;
      return this.dataList.slice(start, end);
    },
    totalPages() {
      return Math.ceil(this.dataList.length / this.pageSize);
    }
  },
  methods: {
    prevPage() {
      if (this.currentPage > 1) this.currentPage--;
    },
    nextPage() {
      if (this.currentPage < this.totalPages) this.currentPage++;
    }
  }
};
</script>

使用第三方库

借助vue-paginate等专门的分页组件快速实现。安装后直接注册组件即可使用。

vue实现翻页效果

npm install vue-paginate
<template>
  <div>
    <paginate
      :page-count="totalPages"
      :click-handler="changePage"
      :prev-text="'<'"
      :next-text="'>'"
    />
    <div v-for="item in paginatedData" :key="item.id">{{ item.name }}</div>
  </div>
</template>

<script>
import Paginate from 'vue-paginate';
export default {
  components: { Paginate },
  methods: {
    changePage(pageNum) {
      this.currentPage = pageNum;
    }
  }
  // 其他逻辑与第一种方法相同
};
</script>

服务端分页

当数据量较大时,建议采用服务端分页。通过API传递页码和每页条数参数,后端返回对应数据。

methods: {
  async fetchData() {
    const res = await axios.get('/api/data', {
      params: {
        page: this.currentPage,
        size: this.pageSize
      }
    });
    this.paginatedData = res.data;
  },
  changePage(pageNum) {
    this.currentPage = pageNum;
    this.fetchData();
  }
}

样式优化

为分页按钮添加CSS样式提升用户体验,例如激活状态高亮、悬停效果等。

button {
  margin: 0 5px;
  padding: 5px 10px;
}
button.active {
  background: #42b983;
  color: white;
}
button:hover:not(.active) {
  background: #ddd;
}

标签: 翻页效果
分享给朋友:

相关文章

vue实现对话框效果

vue实现对话框效果

使用 Vue 实现对话框效果 在 Vue 中实现对话框效果可以通过组件化方式完成,通常结合 v-if/v-show 控制显示隐藏,以及插槽(slot)实现内容自定义。 基础对话框组件实现 创建一个…

vue实现翻页

vue实现翻页

Vue实现翻页功能 在Vue中实现翻页功能通常需要结合分页组件和数据请求逻辑。以下是常见的实现方法: 使用Element UI分页组件 安装Element UI后,可以直接使用其分页组件:…

vue实现吸附效果

vue实现吸附效果

Vue实现吸附效果的方法 吸附效果通常指页面滚动时,某个元素固定在特定位置(如顶部或底部)。以下是几种实现方式: 使用CSS的position: sticky 通过CSS的sticky定位实现吸附效…

vue实现突出效果

vue实现突出效果

Vue 实现突出效果的方法 在 Vue 中实现突出效果可以通过多种方式,包括动态样式绑定、过渡动画、第三方库等。以下是几种常见的方法: 动态样式绑定 通过 v-bind:class 或 v-bind…

css制作卷边效果

css制作卷边效果

使用伪元素和渐变实现卷边效果 通过CSS伪元素和线性渐变可以模拟纸张卷边的视觉效果。这种方法不需要额外元素,仅通过::before或::after伪元素实现。 .element { positi…