前端学习教程-VIte整合ECharts

news/2025/10/4 23:18:21/文章来源:https://www.cnblogs.com/smalldong/p/19126058

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.mzph.cn/news/927675.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

月牙河做网站公司域名对网站排名的影响

2019独角兽企业重金招聘Python工程师标准>>> 软件的一处功能用到EasyUI的表单提交&#xff0c;返回一串字符串&#xff0c;这串字符串里有一段HTML代码&#xff0c;正常的情况下这段HTML代码里的双引号“ 是用 \ 转义过的。在IE中没问题&#xff0c;但是在Firefox和…

网站开发安全管理爬取漫画数据做网站

在项目管理中&#xff0c;图表作为一种直观的工具&#xff0c;帮助项目经理更有效的规划、监控和控制项目的各个方面&#xff0c;以下是项目经理常用的几张图表&#xff0c;它们在项目管理中发挥着至关重要的作用。 1、甘特图 甘特图&#xff08;Gantt Chart&#xff09;是最…

const不可改变解释

不能对const定义的变量本身重新赋值,但是可以通过其他方式更换变量里面的属性或元素(仅限对象类型和数组类型)。 “不能对const定义的变量本身重新赋值”这指的是 const 创建了一个只读的绑定(read-only binding)…

US$137.75 OTOFIX D1 One Year Update Service (Subsription Only)

OTOFIX D1 One Year Update Service (Subsription Only)1. Please send us the device serial number with picture to our Email 2. No Need Shipping. No refund service3. This is Only for Software Update, Witho…

在哪个平台做网站比较好义务网网站建设方案

工作中的焦虑 帮助团队建立复原力、处理不确定性和完成任务的8项策略 作者&#xff1a;阿德里安-戈斯蒂克、切斯特-埃尔顿和安东尼-戈斯蒂克 Anxiety at Work 8 Strategies to Help Teams Build Resilience, Handle Uncertainty, and Get Stuff Done By Adrian Gostick and…

地方门户网站的特点微信开发者模式在哪

从这个类中得到的类图&#xff0c;构划出了软件的大部分设计。 系统结构视图提供软件和整个系统结构最复杂的也是最优雅的描述。和通常的软件系统相比&#xff0c;在分布式嵌入系统中了解系统组件如何协同工作是非常重要的。毕竟&#xff0c;每个类图仅仅是一个系统的静态设计…

macOS Sequoia 15.7.1安全更新:修复字体解析器内存损坏漏洞

苹果发布了macOS Sequoia 15.7.1安全更新,修复了FontParser组件中的越界写入漏洞。该漏洞可能被恶意字体文件利用,导致应用程序意外终止或进程内存损坏。更新可通过Mac App Store或苹果官网下载获取。APPLE-SA-09-29…

AtCoder Beginner Contest 426 ABCDEF 题目解析

A - OS Versions 题意 有三种操作系统的版本,按发布时间顺序分别为 Ocelot、Serval、Lynx。 给定字符串 \(X, Y\),请判断版本 \(X\) 相比于版本 \(Y\) 的发布时间是否相同或更靠后(版本相同或更新)。 思路 直接判断…

前端学习教程-ElementPlus 教程

Element Plus 是基于 Vue 3 的企业级 UI 组件库,提供了丰富的预置组件,可帮助开发者快速构建高质量的前端界面。 一、安装 Element Plus 1. 环境要求Vue 3.0+ Node.js 14.0+2. 安装方式 (1)使用 npm 或 yarn 安装(…

镇江百度网站排名中交路桥建设有限公司官网

Linux磁盘管理&#xff08;二&#xff09;&#xff1a;LVM的创建、格式化和使用 一、LVM原理回顾 LVM的工作原理进行一个总结&#xff1a; (1)物理磁盘被格式化为PV&#xff0c;空间被划分为一个个的PE (2)不同的PV加入到同一个VG中&#xff0c;不同PV的PE全部进入到了VG的PE…

全网网站建设维护wordpress热门文章 图片

BLEU (Bilingual Evaluation Understudy&#xff0c;双语评估基准&#xff09;是一组度量机器翻译和自然语言生成模型性能的评估指标。BLEU指标是由IBM公司提出的一种模型评估方法,以便在机器翻译领域中开发更好的翻译模型。BLEU指标根据生成的句子与人工参考句子之间的词、短语…

AI训练的悖论:为什么越追求准确率越会产生幻觉?

在早期时,我曾让大模型撰写一位冷门历史人物的传记。它胸有成竹,娓娓道来:年代、成就,甚至几句“名言”,一应俱全。读起来简直像历史上真的存在一样。 唯一的问题是:大部分内容都不是真的。严格来说,模型并非“…

完整教程:lesson71:Node.js与npm基础全攻略:2025年最新特性与实战指南

完整教程:lesson71:Node.js与npm基础全攻略:2025年最新特性与实战指南pre { white-space: pre !important; word-wrap: normal !important; overflow-x: auto !important; display: block !important; font-family:…

此网站不支持下载视频怎么办wordpress的文要登录才能看

故障现象  一辆2010款起亚赛拉图车&#xff0c;搭载G4ED 发动机&#xff0c;累计行驶里程约为17.2万km。车主反映&#xff0c;车辆行驶正常&#xff0c;但组合仪表上的发动机转速表指针始终不动。 故障诊断  接车后进行路试&#xff0c;车速表、燃油存量表及发动机冷却温度…

信奥大联赛周赛(提高组)#2516-S 赛后盘点

国庆打的一把奶茶杯,大佬们全都复活了,故窝不占优势 qwq 战果 黄绿蓝紫,250 pts,但是 rk8,被虐爆了。 D1605 E-小梦的密码锁 贪心题,枚举 0~9,求将所有位调成同一个数字需要的操作数,可以通过操作 2 实现单位下…

US$78.85 CG ZA11 BEN.Z(3BTN) 3 Buttons Smart Remote Used with CGDI K2 Remote Key Programmer 5pcs/lot

CG ZA11 BEN.Z(3BTN) 3 Buttons Smart Remote Used with CGDI K2 Remote Key Programmer Package includes:5pc x CG ZA11 BEN.Z(3BTN) 3 Buttons Smart Remote Pictures of CG ZA11 BEN.Z(3BTN) 3 Buttons Smart Remo…

Atcoder Beginner Contest 426 A-D 题解

ACODE #include<bits/stdc++.h> #define usetime() (double)clock () / CLOCKS_PER_SEC * 1000.0 using namespace std; typedef long long LL; void read(int& x){char c;bool f=0;while((c=getchar())<…

网络推广最好的网站有哪些wordpress只显示一个主题

文章目录 SpringSecurity简介快速入门1.准备工作1.2引入SpringSecurity 认证1.登录校验流程2.原理2.1SpringSecurity完整流程2.2认证流程详解 3.解决问题3.1思路分析3.2准备工作3.3.实现3.3.1数据库校验用户3.3.2密码加密存储3.3.3登录接口3.3.4认证过滤器3.3.5退出登录 授权1.…

网站建设维护教程网站开发承诺函

转载于:https://www.cnblogs.com/mountian-lion/p/6353819.html

金融网站建设成功案例做网站具体流程

一、cluster ip Cluster IP 是 Kubernetes 中 Service 的 IP 地址&#xff0c;它是一个虚拟 IP 地址&#xff0c;用于集群内的 Pod 相互通信。 例如&#xff1a; Cluster IP&#xff1a;2.2.2.2负载的真实Pod IP&#xff1a;1.1.1.1 场景&#xff1a; Pod A 的 IP 地址是 …