Vue 分页器 Pagination 实现点击分页器,平滑到对应的dom组件,而不是直接切换对应的组件

实现点击分页器,平滑到对应的dom组件

主要用到的方法:Element.scrollIntoView() 方法让当前的元素滚动到浏览器窗口的可视区域内。

参考网址:https://developer.mozilla.org/zh-CN/docs/Web/API/Element/scrollIntoView

效果图:

首先封装Pagination组件:

因为子组件不能直接修改父组件传递过来的值currentPage,所以先赋值给currentPage1.

<template>
  <div class="pagination">
    <el-pagination
      @current-change="handleCurrentChange"
      :current-page.sync="currentPage1"
      :pageSize="pageSize"
      layout="total, prev, pager, next"
      :total="total"
    ></el-pagination>
  </div>
</template>
<script>
export default {
  props: ['total', 'currentPage', 'pageSize'],
  data() {
    return {
      currentPage1: this.currentPage
    };
  },
  methods: {
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`);
      this.$emit('changePage', val);
    }
  }
};
</script>
<style lang="scss" scoped>
</style>

当点击不同的分页时,父组件将监听组件触发的changePage事件。

<Pagination
      :total="total"
      :page-size="PAGE_SIZE"
      :current-page="currentPage"
      @changePage="handlePage"
></Pagination>
// 分页只重新获取歌单
handlePage(val) {
      console.log(val);
      this.currentPage = val;
      this.getPlaylists();
      scrollInto(this.$refs.playlists);
}

scrollInto:滑到对应的DOM元素上

export function scrollInto(dom) {
  dom.scrollIntoView({ behavior: 'smooth' });
}
原文地址:https://www.cnblogs.com/hahahakc/p/13142022.html