当前位置: 首页 > news >正文

前端学习教程-VIte整合ECharts

ECharts 是一个强大的开源数据可视化库,而 Vite 是现代前端构建工具,两者结合可以高效开发数据可视化应用。本教程实现从创建 Vite 项目到使用 ECharts 实现各种图表。

一、环境准备

1. 创建 Vite 项目

首先确保已安装 Node.js (v14.18+),然后执行以下命令创建 Vite 项目:

# 创建项目
npm create vite@latest echarts-demo -- --template vue# 进入项目目录
cd echarts-demo# 安装依赖
npm install

2. 安装 ECharts

在项目中安装 ECharts:

npm install echarts --save

二、基本使用:创建第一个图表

1. 全局引入 ECharts(简单项目推荐)

在入口文件中全局引入 ECharts,方便在整个项目中使用(main.js):

import { createApp } from 'vue'
import App from './App.vue'
import * as echarts from 'echarts'  // 引入 EChartsconst app = createApp(App)// 将 ECharts 挂载到全局
app.config.globalProperties.$echarts = echartsapp.mount('#app')

2. 创建基础图表组件

创建一个简单的折线图组件,展示 ECharts 的基本用法:

<template><!-- 图表容器,必须指定宽高 --><div class="chart-container" ref="chartRef"></div>
</template><script setup>
import { ref, onMounted, onUnmounted, getCurrentInstance } from 'vue'// 获取图表容器
const chartRef = ref(null)
// 图表实例
let chartInstance = null// 获取全局的 echarts
const { proxy } = getCurrentInstance()
const echarts = proxy.$echarts// 初始化图表
const initChart = () => {// 创建图表实例chartInstance = echarts.init(chartRef.value)// 图表配置项const option = {title: {text: '月度销售额趋势',left: 'center'},tooltip: {trigger: 'axis'  // 坐标轴触发提示},legend: {data: ['销售额'],top: 30},grid: {left: '3%',right: '4%',bottom: '3%',containLabel: true},xAxis: {type: 'category',boundaryGap: false,data: ['1月', '2月', '3月', '4月', '5月', '6月']},yAxis: {type: 'value',name: '销售额 (万元)'},series: [{name: '销售额',type: 'line',  // 折线图data: [120, 190, 130, 150, 220, 280],smooth: true,  // 平滑曲线markPoint: {data: [{ type: 'max', name: '最大值' },{ type: 'min', name: '最小值' }]},markLine: {data: [{ type: 'average', name: '平均值' }]}}]}// 设置图表配置chartInstance.setOption(option)
}// 监听窗口大小变化,重绘图表
const handleResize = () => {chartInstance?.resize()
}// 组件挂载时初始化图表
onMounted(() => {initChart()window.addEventListener('resize', handleResize)
})// 组件卸载时销毁图表
onUnmounted(() => {window.removeEventListener('resize', handleResize)if (chartInstance) {chartInstance.dispose()  // 销毁实例,释放资源chartInstance = null}
})
</script><style scoped>
.chart-container {width: 100%;height: 400px;  /* 必须设置高度 */margin: 20px auto;
}
</style>

3. 在页面中使用图表组件

在 App.vue 中引入并使用折线图组件:

<template><div id="app"><h1>ECharts 数据可视化示例</h1><LineChart /></div>
</template><script setup>
import LineChart from './components/LineChart.vue'
</script><style>
#app {max-width: 1200px;margin: 0 auto;padding: 20px;
}h1 {text-align: center;color: #333;
}
</style>

三、按需引入 ECharts(推荐生产环境使用)

ECharts 完整包体积较大,按需引入可减小打包体积,只引入需要的模块:

<template><div class="chart-container" ref="chartRef"></div>
</template><script setup>
import { ref, onMounted, onUnmounted } from 'vue'
// 按需引入 ECharts 核心模块和所需图表
import * as echarts from 'echarts/core'
import { BarChart } from 'echarts/charts'  // 柱状图
import {TitleComponent,TooltipComponent,GridComponent,LegendComponent
} from 'echarts/components'
import { CanvasRenderer } from 'echarts/renderers'// 注册所需的组件
echarts.use([TitleComponent,TooltipComponent,GridComponent,LegendComponent,BarChart,CanvasRenderer
])// 图表容器和实例
const chartRef = ref(null)
let chartInstance = null// 初始化图表
const initChart = () => {chartInstance = echarts.init(chartRef.value)const option = {title: {text: '产品销量对比',left: 'center'},tooltip: {trigger: 'axis',axisPointer: { type: 'shadow' }},legend: {data: ['线上', '线下'],top: 30},grid: {left: '3%',right: '4%',bottom: '3%',containLabel: true},xAxis: {type: 'category',data: ['产品A', '产品B', '产品C', '产品D', '产品E']},yAxis: {type: 'value',name: '销量 (件)'},series: [{name: '线上',type: 'bar',data: [1200, 1900, 1500, 2400, 1800],itemStyle: { color: '#42b983' }},{name: '线下',type: 'bar',data: [800, 1500, 1200, 1800, 2200],itemStyle: { color: '#3b82f6' }}]}chartInstance.setOption(option)
}// 响应式处理
const handleResize = () => {chartInstance?.resize()
}onMounted(() => {initChart()window.addEventListener('resize', handleResize)
})onUnmounted(() => {window.removeEventListener('resize', handleResize)chartInstance?.dispose()
})
</script><style scoped>
.chart-container {width: 100%;height: 400px;
}
</style>

四、动态数据更新

ECharts 支持动态更新数据,通过重新设置 option 即可实现:

<template><div><div class="chart-container" ref="chartRef"></div><div class="controls"><el-button type="primary" @click="updateData">更新数据</el-button><el-button @click="randomizeData">随机数据</el-button></div></div>
</template><script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import * as echarts from 'echarts'const chartRef = ref(null)
let chartInstance = null
let currentData = [120, 190, 130, 150, 220, 280]// 初始化图表
const initChart = () => {chartInstance = echarts.init(chartRef.value)updateChart()  // 初始化图表数据
}// 更新图表配置
const updateChart = () => {const option = {title: { text: '动态数据演示', left: 'center' },tooltip: { trigger: 'axis' },xAxis: { type: 'category', data: ['1月', '2月', '3月', '4月', '5月', '6月'] },yAxis: { type: 'value' },series: [{type: 'line',data: currentData,smooth: true}]}chartInstance.setOption(option)
}// 更新为固定数据
const updateData = () => {currentData = [150, 230, 180, 270, 210, 320]updateChart()  // 重新设置配置,更新图表
}// 生成随机数据
const randomizeData = () => {currentData = currentData.map(() => Math.floor(Math.random() * 300) + 50)updateChart()
}// 组件生命周期处理
onMounted(() => {initChart()window.addEventListener('resize', () => chartInstance?.resize())
})onUnmounted(() => {chartInstance?.dispose()
})
</script><style scoped>
.chart-container {width: 100%;height: 400px;
}.controls {text-align: center;margin-top: 20px;
}button {margin: 0 10px;padding: 8px 16px;
}
</style>

五、常见问题与优化

1. 图表不显示?

  • 确保图表容器设置了明确的宽高(不能是 height: 100% 而父元素没有高度)
  • 检查是否在组件挂载后(onMounted)才初始化图表

2. 优化打包体积

  • 使用按需引入方式,只导入需要的图表和组件
  • 生产环境构建时启用 tree-shaking(Vite 默认支持)

3. 性能优化

  • 频繁更新数据时,可使用 chartInstance.setOption(option, { notMerge: true }) 避免配置合并
  • 不需要的图表及时调用 dispose() 销毁,释放内存
  • 大数据量时使用 ECharts 的渐进式渲染或数据采样

总结

  • Vite 项目中安装和引入 ECharts 的两种方式(全局引入 / 按需引入)
  • 基本图表的创建和配置
  • 图表的响应式处理(窗口大小变化)
  • 动态更新图表数据的方法
  • 常见问题的解决和优化技巧
http://www.gsyq.cn/news/15886.html

相关文章:

  • Atcoder Beginner Contest 426 A-D 题解
  • mtgsig
  • 详细介绍:Java-Spring 入门指南(十七)SpringMVC--Apipostl与RestFul实战测试
  • 高中数列梳理
  • 详细介绍:告别 403 Forbidden!详解爬虫如何模拟浏览器头部(User-Agent)
  • AtCoder Beginner Contest 426 实况记录 + A-D 题解
  • 提示词攻击如何防范(2025):从 Indirect Prompt Injection 到 RAG 供应链的分层防御实战
  • 但行好事,莫问前程
  • 前端学习教程-环境配置
  • 微分和积分的区别
  • 202509_QQ_secret
  • Matlab R2024b下载及详细安装教程,附永久免费Matlab安装包
  • 数据结构 - 跳表 Skip List
  • 06. 定时器
  • NOIP之前的复健记录
  • 解码Huffman 编码与 Huffman 树
  • 深入解析:SAE J3072-2024插电式电动汽车(PEV)中的车载逆变器系统安全标准介绍
  • 实用指南:gitlab-runner 再次实践中理解和学习
  • 【自然语言处理】文本规范化知识点梳理与习题总结 - 教程
  • Rocky Linux 8 远程管理配置指南(宿主机 VNC + KVM 虚拟机 VNC) - 指南
  • 邮票收集问题正推证明
  • 2025 年 9 月习题集
  • 实用指南:Linux整个系统权限玩坏了怎么办
  • C# 代码规范
  • MySql的存储过程以及JDBC实战 - 详解
  • [MCP] 监听资源更新
  • 【C++哲学】面向对象的三大特性之 多态 - 实践
  • 2025CSP-S模拟赛58 比赛总结
  • 单一训练模式适应多个机器人本体 —— skiled brain —— 机器人酷刑现场,竟是为了锻造全能大脑,网友:求AGI饶了我
  • 2025/10/4 总结