Skip to content

前端自己分页和筛选

继上次前端自行分页后,查询自然也不能给后端执行。

那么前端如何自己做多条件查询呢?

刚开始没有头绪,后来发现可以把【查询条件定死】,就变得非常舒服了。

用到两个工具:

  1. Vue 的计算属性: computed
  2. JS ES6的方法:filter

筛选步骤

元数据已知是 tableData.value,这个不能动,因为后面还需要进行重置。

新造一个数组 filtteredArr 来存放过滤后的列表:

js
const filtteredArr = ref([])

然后用计算属性写过滤:

js
// 搜索项,定死两项
const searchInfo = ref({
  tplSource: '',
  tplCode: ''
})

const computedValue = computed(() => {
	// 这里对搜索项统一处理为小写 
  const sourceFilter = searchInfo.value.tplSource.toLowerCase();
  const tplCodeFilter = searchInfo.value.tplCode.toLowerCase();
  
  return tableData.value.filter(data => {
	  // 循环tableData,将每一项的需要查询的值处理为小写 
    const tplSource = data.tplSource.toLowerCase();
    const tplCode = data.tplCode.toLowerCase();
    // 根据条件进行筛选
    return (!sourceFilter || tplSource.includes(sourceFilter) &&
      (!tplCodeFilter || tplCode.includes(tplCodeFilter));
      // 如果某一个搜索项为空,例如 !sourceFilter 的值就是true,则跳过该字段的搜索
  });
});

完整代码

js
const searchInfo = ref({
  tplSource: '',
  tplCode: ''
})

// 重置
const onReset = () => {
  searchInfo.value = {
    tplSource: '',
    tplCode: ''
  }
  loading.value = true
  setTimeout(() => {
    filtteredArr.value = tableData.value // 重新赋值
    loading.value = false
  }, 500);
  // getTableData()
}
const filtteredArr = ref([])

const computedValue = computed(() => {
  const sourceFilter = searchInfo.value.tplSource.toLowerCase();
  const tplCodeFilter = searchInfo.value.tplCode.toLowerCase();
  return tableData.value.filter(data => {
    const tplSource = data.tplSource.toLowerCase();
    const tplCode = data.tplCode.toLowerCase();
    // 根据条件进行筛选
    return (!sourceFilter || tplSource.includes(sourceFilter) &&
      (!tplCodeFilter || tplCode.includes(tplCodeFilter));
  });
});


// 搜索
const onSubmit = () => {
  page.value = 1
  pageSize.value = 10
  loading.value = true
  setTimeout(() => {
    filtteredArr.value = computedValue.value
    total.value = filtteredArr.value.length
    loading.value = false
  }, 500);

  // getTableData() 
}

// 分页
const handleSizeChange = (val) => {
  pageSize.value = val
  // getTableData()
}

// 修改页面容量
const handleCurrentChange = (val) => {
  page.value = val
  // getTableData()
}

// 查询
const getTableData = async () => {
  loading.value = true
  const table = await getThingTemplateList({ page: page.value, pageSize: pageSize.value, ...searchInfo.value })
  if (table.code === 0) {
    filtteredArr.value = tableData.value = table.data.list
    total.value = table.data.total
    // page.value = table.data.page
    // pageSize.value = table.data.pageSize
  }

  setTimeout(() => {
    loading.value = false
  }, 100);
}

template部分

html
<el-table ref="multipleTable" :data="filtteredArr.slice((page - 1) * pageSize, page * pageSize)" row-key="ID" v-loading="loading"  @current-change="handleCurChange" @selection-change="handleSelectionChange" align="center">

Released under the MIT License.