Vue3在Element UI 表格中自定義時間格式化顯示
- 一、前言
- 1、準備工作
- 2、實現步驟
- 1. 引入 Element UI 組件
- 2. 自定義時間格式化函數
- 3. 格式化日期邏輯
- 3、完整示例
- 4、結論
一、前言
在開發 Web 應用程序時,常常需要在表格中展示時間數據。Element UI 是一個流行的 Vue UI 組件庫,它提供了一系列易于使用的表格組件,但是在展示時間數據時,默認的格式可能不符合你的需求。本文將介紹如何使用 Element UI 的自定義模板來格式化時間數據,以滿足特定的展示需求。
1、準備工作
首先,確保你的項目已經集成了 Element UI。如果沒有,你可以通過 npm 或 yarn 安裝 Element Plus:
npm install element-plus --save
# 或者
yarn add element-plus
2、實現步驟
1. 引入 Element UI 組件
在你的 Vue 組件中引入 Element UI 的表格組件:
<template><el-table :data="tableData"><el-table-column prop="date" label="時間" :formatter="formatDate"></el-table-column></el-table>
</template><script setup>
import { ref } from 'vue';
import { ElTable } from 'element-plus';const tableData = ref([{ id: 1, date: '2024-05-25T12:00:00Z' },{ id: 2, date: '2024-05-26T15:30:00Z' },
]);
</script>
2. 自定義時間格式化函數
在 <script setup>
區域中定義一個函數,用于將時間格式化為所需的格式:
<script setup>
import { ref } from 'vue';
import { ElTable } from 'element-plus';const tableData = ref([{ id: 1, date: '2024-05-25T12:00:00Z' },{ id: 2, date: '2024-05-26T15:30:00Z' },
]);const formatDate = (row, column) => {const date = new Date(row[column.property]);return formatDateString(date);
};const formatDateString = (date) => {// 格式化日期邏輯
};
</script>
3. 格式化日期邏輯
編寫一個函數來格式化日期,以滿足你的需求。例如,將日期格式化為 年-月-日-時-分-秒
:
<script setup>
// 其他代碼...const formatDateString = (date) => {const year = date.getFullYear();const month = pad2(date.getMonth() + 1);const day = pad2(date.getDate());const hours = pad2(date.getHours());const minutes = pad2(date.getMinutes());const seconds = pad2(date.getSeconds());return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};const pad2 = (number) => {return (number < 10 ? '0' : '') + number;
};
</script>
3、完整示例
<template><el-table :data="tableData"><el-table-column prop="date" label="時間" :formatter="formatDate"></el-table-column></el-table>
</template><script setup>
import { ref } from 'vue';
import { ElTable } from 'element-plus';const tableData = ref([{ id: 1, date: '2024-05-25T12:00:00Z' },{ id: 2, date: '2024-05-26T15:30:00Z' },
]);const formatDate = (row, column) => {const date = new Date(row[column.property]);return formatDateString(date);
};const formatDateString = (date) => {const year = date.getFullYear();const month = pad2(date.getMonth() + 1);const day = pad2(date.getDate());const hours = pad2(date.getHours());const minutes = pad2(date.getMinutes());const seconds = pad2(date.getSeconds());return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};const pad2 = (number) => {return (number < 10 ? '0' : '') + number;
};
</script>
4、結論
通過自定義 formatter
函數,你可以輕松地在 Element UI 表格中格式化時間數據,以滿足你的特定需求。這種靈活