在前端开发中,时间轴(Timeline)是一种常见且有效的方式来展示时间相关的数据。在本篇文章中,我们将展示如何在 Vue 3 项目中使用 ECharts 创建一个具有动态时间范围的时间轴,并添加了今日时间的标记以及通过按钮来前进和后退调整时间范围的功能。
前言
时间轴的可视化是展示与时间相关信息的重要方式,常常用于展示事件、任务进度、数据变化等。在这篇文章中,我们将实现一个交互式的时间轴,支持动态的时间范围选择、显示今日时间,并且通过前后按钮来调整时间范围。
主要功能
- 显示具有时间段的自定义时间轴。
- 动态更新 X 轴的时间范围。
- 显示今日时间。
- 使用按钮进行前进和后退的时间范围调整。
效果图
1. 安装必要的依赖
首先,确保你的 Vue 3 项目已经安装了 ECharts。如果没有安装,可以通过以下命令安装:
npm install vue@next npm install echarts
如果你还没有创建 Vue 3 项目,可以使用 Vue CLI 创建一个新的项目:
npm install -g @vue/cli vue create vue-echarts-timeline
然后选择 Vue 3 配置。
2. 创建 Vue 3 组件
在组件中,我们将使用 ECharts 的 custom
类型来绘制时间轴。以下是实现的基本步骤和代码。
2.1 完整代码
在 script setup
中,我们将初始化 ECharts,并根据时间段数据渲染时间轴。X 轴使用动态的时间范围,并且会在图表中标记今日时间。
<!--
* @Author: 彭麒
* @Date: 2024/12/24
* @Email: 1062470959@qq.com
* @Description: 此源码版权归吉檀迦俐所有,可供学习和借鉴或商用。
-->
<template>
<div class="content">
<button class="back-button" @click="goBack">返回</button>
<div class="font-bold text-[24px]">在Vue3中使用Echarts实现时间轴效果</div>
<div class="mt-[202px] px-10">
<div class="w-full mx-auto p-4">
<div class="relative">
<!-- Timeline Bar -->
<div ref="chartContainer" class="w-full h-[200px]"></div>
<button
@click="navigatePrev"
class="absolute left-0 top-1/2 -translate-y-1/2 -translate-x-12 bg-white rounded-full p-2 shadow-lg hover:bg-gray-50"
>
<svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6 text-gray-600" fill="none" viewBox="0 0 24 24"
stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7"/>
</svg>
</button>
<button
@clic