Vue+Element表格本地分页过滤

关键点

  1. 过滤:全量数据单独保存,增加计算属性根据过滤条件计算过滤后的表格数据tableData。
  2. 分页:增加一个计算属性pageData,根据当前页号currentPage和每页大小pageSize从表格数组里过滤出当前页的数据。分页条的总行数设为过滤后的数据的条数。

代码

<template>
<section >
  <el-form :inline="true" :model="filters" @submit.native.prevent >
    <el-form-item label="姓名" >
      <el-input v-model="filters.name" placeholder="姓名" >el-input >
    el-form-item >
  el-form>
  <el-table :data="pageData" border style="width: 100%">
    <el-table-column prop="date" label="日期" width="180">el-table-column>
    <el-table-column prop="name" label="姓名" width="180">el-table-column>
    <el-table-column prop="address" label="地址">el-table-column>
  el-table>
  <el-pagination layout="total, sizes, prev, pager, next, jumper"
                 @current-change="handleCurrentChange"
                 @size-change="handleSizeChange"
                 :page-sizes="[2,10, 20, 50]"
                 :page-size="pageSize"
                 :total="tableData.length" style="float:right;" >
  el-pagination >
section >
template>

<script>
export default {
    data() {
      return {
        filters: {
          name:''
        },
        currentPage: 1,
        pageSize: 2,
        allData: [{
          date: '2016-05-02',
          name: '王小虎',
          address: '上海市普陀区金沙江路 1518 弄'
        }, {
          date: '2016-05-04',
          name: '李小龙',
          address: '上海市普陀区金沙江路 1517 弄'
        }, {
          date: '2016-05-01',
          name: '张麻子',
          address: '上海市普陀区金沙江路 1519 弄'
        }, {
          date: '2016-05-03',
          name: '王二小',
          address: '上海市普陀区金沙江路 1516 弄'
        }]
      }
    },
    computed: {
      tableData: function() {
        return this.allData.filter(item => {
          if (this.filters.name) {
            if (!(item.name && item.name.includes(this.filters.name))) {
              return false
            }
          }
          return true
        })
      },
      pageData: function() {
        return this.tableData.slice((this.currentPage - 1) * this.pageSize, this.currentPage * this.pageSize)
      }
    },
    methods: {
      handleCurrentChange(val) {
        this.currentPage = val
      },
      handleSizeChange(val) {
        this.currentPage = 1
        this.pageSize = val
      }
    }
  }
script>

在线运行

你可能感兴趣的:(javascript,vue,elementui)