当前位置: 首页 > 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.hskmm.com/?act=detail&tid=24530

相关文章:

  • const不可改变解释
  • macOS Sequoia 15.7.1安全更新:修复字体解析器内存损坏漏洞
  • AtCoder Beginner Contest 426 ABCDEF 题目解析
  • 数学
  • 前端学习教程-ElementPlus 教程
  • AI训练的悖论:为什么越追求准确率越会产生幻觉?
  • 信奥大联赛周赛(提高组)#2516-S 赛后盘点
  • PSRAM 是什么
  • Debian 13 eza 安装与常用参数
  • Syncthing 2.0 版本开机自启
  • 鲜花 10.4:【半 whk 向】临项交换法贪心
  • 前端学习教程-Pinia 教程
  • 布谷娱乐直播架构源码开发实用功能:技术驱动更迭的创新体验
  • Bean生命周期
  • 回忆QQ空间有感
  • mtgsig
  • 前端学习教程-Vue Router 教程
  • 详细介绍:Java-Spring 入门指南(十七)SpringMVC--Apipostl与RestFul实战测试
  • 详细介绍:告别 403 Forbidden!详解爬虫如何模拟浏览器头部(User-Agent)
  • 通过学习分位数函数提升预测准确性
  • 高中数列梳理
  • AtCoder Beginner Contest 426 实况记录 + A-D 题解
  • 提示词攻击如何防范(2025):从 Indirect Prompt Injection 到 RAG 供应链的分层防御实战
  • 【STM32项目开源】基于STM32的智能养殖场环境监测系统 - 详解
  • 前端学习教程-Axios
  • 『回忆录』返校前夜 230102
  • 断更
  • 前端学习教程-环境配置
  • TypeScript - Ref
  • 20251004 qmd 弱化规约(未完成)