首页 星云 工具 资源 星选 资讯 热门工具
:

PDF转图片 完全免费 小红书视频下载 无水印 抖音视频下载 无水印 数字星空

Vue Hook 封装通用型表格

编程知识
2024年08月01日 19:04

一、创建通用型表格的需求

实现一个通用型表格组件,具备以下功能:

  1. 动态列配置。
  2. 分页功能。
  3. 排序功能。
  4. 可扩展的行操作功能。

二、设计通用型表格组件

首先,需要设计一个基础的表格组件,它接受列配置、数据和分页信息等参数。

1. 创建 useTable Hook

src/hooks 目录下创建 useTable.js 文件:

import { ref, reactive, onMounted, toRefs } from 'vue';

export function useTable(fetchData) {
  const state = reactive({
    loading: false,
    data: [],
    pagination: {
      currentPage: 1,
      pageSize: 10,
      total: 0,
    },
    sort: {
      field: '',
      order: '',
    },
  });

  const loadData = async () => {
    state.loading = true;
    const { currentPage, pageSize } = state.pagination;
    const { field, order } = state.sort;
    const result = await fetchData(currentPage, pageSize, field, order);
    state.data = result.data;
    state.pagination.total = result.total;
    state.loading = false;
  };

  const changePage = (page) => {
    state.pagination.currentPage = page;
    loadData();
  };

  const changePageSize = (size) => {
    state.pagination.pageSize = size;
    loadData();
  };

  const changeSort = (field, order) => {
    state.sort.field = field;
    state.sort.order = order;
    loadData();
  };

  onMounted(() => {
    loadData();
  });

  return {
    ...toRefs(state),
    loadData,
    changePage,
    changePageSize,
    changeSort,
  };
}

 

 

2. 创建 TableComponent.vue

src/components 目录下创建 TableComponent.vue 文件:

<template>
  <div>
    <table>
      <thead>
        <tr>
          <th v-for="col in columns" :key="col.key" @click="changeSort(col.key)">
            {{ col.title }}
            <span v-if="sort.field === col.key">{{ sort.order === 'asc' ? '↑' : '↓' }}</span>
          </th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="row in data" :key="row.id">
          <td v-for="col in columns" :key="col.key">{{ row[col.key] }}</td>
        </tr>
      </tbody>
    </table>
    <div class="pagination">
      <button @click="changePage(pagination.currentPage - 1)" :disabled="pagination.currentPage === 1">Previous</button>
      <span>{{ pagination.currentPage }} / {{ Math.ceil(pagination.total / pagination.pageSize) }}</span>
      <button @click="changePage(pagination.currentPage + 1)" :disabled="pagination.currentPage === Math.ceil(pagination.total / pagination.pageSize)">Next</button>
    </div>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue';
import { useTable } from '@/hooks/useTable';

export default {
  props: {
    fetchData: {
      type: Function,
      required: true,
    },
    columns: {
      type: Array,
      required: true,
    },
  },
  setup(props) {
    const { data, loading, pagination, sort, loadData, changePage, changePageSize, changeSort } = useTable(props.fetchData);

    return {
      data,
      loading,
      pagination,
      sort,
      loadData,
      changePage,
      changePageSize,
      changeSort,
    };
  },
};
</script>

<style scoped>
.pagination {
  display: flex;
  justify-content: center;
  margin-top: 10px;
}
</style>

 

三、使用通用型表格组件

在实际项目中,可以这样使用这个通用型表格组件:

1. 创建 ExampleTable.vue 组件

src/views 目录下创建 ExampleTable.vue 文件:

<template>
  <div>
    <TableComponent :fetchData="fetchData" :columns="columns" />
  </div>
</template>

<script>
import TableComponent from '@/components/TableComponent.vue';

export default {
  components: {
    TableComponent,
  },
  setup() {
    const columns = [
      { key: 'name', title: 'Name' },
      { key: 'age', title: 'Age' },
      { key: 'email', title: 'Email' },
    ];

    const fetchData = async (page, pageSize, sortField, sortOrder) => {
      // 模拟数据获取
      const total = 100;
      const data = Array.from({ length: pageSize }, (v, i) => ({
        id: (page - 1) * pageSize + i + 1,
        name: `Name ${(page - 1) * pageSize + i + 1}`,
        age: 20 + ((page - 1) * pageSize + i + 1) % 30,
        email: `user${(page - 1) * pageSize + i + 1}@example.com`,
      }));
      return { data, total };
    };

    return {
      columns,
      fetchData,
    };
  },
};
</script>

 

四、解释代码

  1. 定义 useTable Hook

    • 使用 Vue 的 refreactive 定义表格状态。
    • 定义 loadDatachangePagechangePageSizechangeSort 函数来处理数据加载和分页、排序变化。
    • 使用 onMounted 生命周期钩子在组件挂载时加载数据。
  2. 定义 TableComponent 组件

    • 接受 fetchDatacolumns 作为组件属性。
    • 使用 useTable Hook 获取表格数据和操作函数。
    • 渲染表格头部、主体和分页组件,并绑定相关事件。
  3. 使用通用型表格组件

    • ExampleTable.vue 中定义列配置和数据获取函数。
    • 使用 TableComponent 并传递 fetchDatacolumns 属性。

 

From:https://www.cnblogs.com/zx618/p/18337389
本文地址: http://www.shuzixingkong.net/article/675
0评论
提交 加载更多评论
其他文章 在Python中使用sqlalchemy来操作数据库的几个小总结
在探索使用 FastAPI, SQLAlchemy, Pydantic,Redis, JWT 构建的项目的时候,其中数据库访问采用SQLAlchemy,并采用异步方式。数据库操作和控制器操作,采用基类继承的方式减少重复代码,提高代码复用性。在这个过程中设计接口和测试的时候,对一些问题进行跟踪解决,并
ThinkPHP6支持金仓数据库(Kingbase)解决无法使用模型查询问题
参考了很多前人的文章,最后只支持Db::query原生查询,不支持thinkphp数据模型方法,这在实际项目中是很难接受的,特分享出解决方案。 先按照流程配置如下: 1.准备工作 首先确认PHP支持金仓数据库的扩展,可以去金仓官网下载,安装配置(详细配置略过……)。 使用 php -m 命令检查,显
ThinkPHP6支持金仓数据库(Kingbase)解决无法使用模型查询问题 ThinkPHP6支持金仓数据库(Kingbase)解决无法使用模型查询问题 ThinkPHP6支持金仓数据库(Kingbase)解决无法使用模型查询问题
为团队配置Linux环境,简单高效的项目共享方案
前言 最近好久没写博客了,事情太多了,我还搞了个新的好玩的项目,等后续做得差不多了来写篇文章介绍一下。 在我们目前的AI项目中,团队需要共同使用一台GPU服务器来做模型训练和数据处理。为了让每个团队成员都能高效地使用这台服务器,我们决定设置一个多用户共享环境。这样,无论是代码开发、模型测试还是结果验
比较基因组学流程
1、OrthoFinder 教程:用于比较基因组学的系统发育直系学推断 1.1 orthofinder介绍 OrthoFinder是一种快速、准确和全面的比较基因组学分析工具。它可以找到直系和正群,为所有的正群推断基因树,并为所分析的物种推断一个有根的物种树。OrthoFinder还为比较基因组分析
比较基因组学流程 比较基因组学流程 比较基因组学流程
Jenkins 配置即代码(Configuration as Code)详解
1、概述 在《Centos7下安装配置最新版本Jenkins(2.452.3)》这篇博文中讲解了如何安装Jenkins,虽然在安装Jenkins时安装了一些必备的推荐插件,但在企业环境中使用Jenkins之前,我们仍需完成一系列手动配置工作,如配置 System Configuration、Secu
Jenkins 配置即代码(Configuration as Code)详解 Jenkins 配置即代码(Configuration as Code)详解 Jenkins 配置即代码(Configuration as Code)详解
LangChain的LCEL和Runnable你搞懂了吗
LangChain的LCEL估计行业内的朋友都听过,但是LCEL里的RunnablePassthrough、RunnableParallel、RunnableBranch、RunnableLambda又是什么意思?什么场景下用?
LangChain的LCEL和Runnable你搞懂了吗 LangChain的LCEL和Runnable你搞懂了吗 LangChain的LCEL和Runnable你搞懂了吗
运行期加载时共享库路径搜索优先级实验
目录前言实验环境目录说明单独测试不配置路径默认路径ld.so.cacheRUNPATHLD_LIBRARY_PATHRPATH优先级测试附录库文件源码主程序源码makefile脚本run_nonerun_defaultrun_ld_so_cacherun_runpathrun_ld_library_
架构演化学习思考(3)
架构演化学习思考(3) 接上一篇我们继续对命令模式进行学习。 在这节内容中,我们聊一下经典的命令模式,还记得上一篇文章开头我们实现的简单的命令模式吗?来看代码,非常简单易解。 public interface ICommand { void Execute(); } public class Pla
架构演化学习思考(3)