Vue 引入 ECharts

在 Vue3 中使用 ECharts 可以通过以下步骤实现,这里为你提供一个完整的集成指南:


1. 安装 ECharts

vue 复制代码
npm install echarts --save
  # 或
yarn add echarts

2. 基础使用(直接在组件中)

vue 复制代码
<template>
  <div ref="chartDom" style="width: 600px; height: 400px"></div>
</template>
<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import * as echarts from 'echarts'

const chartDom = ref(null)
let myChart = null

// 初始化图表
const initChart = () => {
  myChart = echarts.init(chartDom.value)
  // 配置项对象
  const option = {
    title: { text: '示例图表' },
    tooltip: {},
    xAxis: { data: ['衬衫', '羊毛衫', '雪纺衫', '裤子', '高跟鞋', '袜子'] },
    yAxis: {},
    series: [{
      name: '销量',
      type: 'bar',
      data: [5, 20, 36, 10, 10, 20]
    }]
  }
  //使用配置
  myChart.setOption(option)
}

// 生命周期钩子
onMounted(() => {
  //挂载后才能操作DOM
  initChart()
})

onUnmounted(() => {
  if (myChart) {
    myChart.dispose() // 销毁实例
  }
})
</script>

3. 创建可复用图表组件(推荐)

vue 复制代码
<!-- components/EChartsWrapper.vue -->
<template>
  <div ref="chartContainer" :style="{ width, height }"></div>
</template>
<script setup>
import { ref, watch, onBeforeUnmount } from 'vue'
import * as echarts from 'echarts'

const props = defineProps({
  option: {
    type: Object,
    required: true
  },
  width: {
    type: String,
    default: '100%'
  },
  height: {
    type: String,
    default: '400px'
  }
})

const chartContainer = ref(null)
let chartInstance = null

// 初始化图表
const initChart = () => {
  chartInstance = echarts.init(chartContainer.value)
  chartInstance.setOption(props.option)
}

// 监听配置变化
watch(
  () => props.option,
  (newVal) => {
    chartInstance?.setOption(newVal)
  },
  { deep: true }
)

// 生命周期
onBeforeUnmount(() => {
  chartInstance?.dispose()
})

// 初始化
initChart()
</script>

4. 在父组件中使用

vue 复制代码
<template>
  <EChartsWrapper :option="chartOption" />
</template>
<script setup>
import EChartsWrapper from './components/EChartsWrapper.vue'

const chartOption = {
  title: { text: '动态更新示例' },
  tooltip: { trigger: 'axis' },
  xAxis: { type: 'category', data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'] },
  yAxis: { type: 'value' },
  series: [{
    data: [120, 200, 150, 80, 70, 110, 130],
    type: 'line',
    smooth: true
  }]
}
</script>

5. 高级用法技巧

动态更新数据

vue 复制代码
// 在组件中
    const updateData = () => {
    const newData = [Math.random() * 100, ...chartOption.series[0].data.slice(0,6)]
    chartOption.series[0].data = newData
    }

按需引入减小体积

vue 复制代码
// 只引入需要的模块
    import { use } from 'echarts/core'
    import { CanvasRenderer } from 'echarts/renderers'
    import { BarChart } from 'echarts/charts'
    import {
    TitleComponent,
    TooltipComponent,
    GridComponent
    } from 'echarts/components'

    use([
    CanvasRenderer,
    BarChart,
    TitleComponent,
    TooltipComponent,
    GridComponent
    ])

响应式容器

vue 复制代码
<template>
  <div class="chart-container">
    <EChartsWrapper :option="chartOption" />
  </div>
</template>
<style>
.chart-container {
  width: 100%;
  height: 50vh;
  padding: 20px;
  box-sizing: border-box;
}
</style>

核心配置项分类

  1. 标题 (title)
vue 复制代码
title: {
  text: '主标题',          // 主标题文本
    subtext: '副标题',      // 副标题文本
    left: 'center',         // 标题位置(left/center/right)
    textStyle: {            // 文本样式
    color: '#333',
      fontSize: 18
  }
}
  1. 图例 (legend)
vue 复制代码
legend: {
  data: ['销量', '库存'], // 图例项名称数组
    top: 'bottom',          // 位置(top/bottom/left/right)
    orient: 'horizontal'    // 布局方向(horizontal/vertical)
}
  1. 坐标轴 (xAxis/yAxis)
vue 复制代码
xAxis: {
  type: 'category',       // 坐标轴类型(category/value/time等)
    data: ['衬衫', '羊毛衫'], // 类别数据(仅 category 类型需要)
    name: '产品',            // 坐标轴名称
    axisLabel: {            // 坐标轴标签配置
    rotate: 45            // 标签旋转角度
  }
}
  1. 系列 (series)
vue 复制代码
series: [{
  name: '销量',            // 系列名称(对应图例)
  type: 'bar',            // 图表类型(bar/line/pie等)
  data: [5, 20, 36],      // 数据数组
  smooth: true,           // 是否平滑曲线(仅 line 有效)
  itemStyle: {            // 图形样式
    color: '#5470c6'
  },
  label: {                // 数据标签配置
    show: true,
    position: 'top'
  }
}]
  1. 提示框 (tooltip)
vue 复制代码
tooltip: {
  trigger: 'axis',        // 触发类型(axis/item)
    formatter: '{b}: {c}'   // 格式化函数({a}系列名, {b}数据名, {c}数值)
}
  1. 工具箱 (toolbox)
vue 复制代码
toolbox: {
  feature: {
    saveAsImage: {},      // 保存图片
    dataView: {},         // 数据视图
    restore: {}           // 重置配置
  }
}

其他重要配置

  • 颜色调色板 :通过 color 数组定义全局颜色序列
vue 复制代码
color: ['#5470c6', '#91cc75', '#fac858']
  • 响应式设计 :使用 grid 控制图表区域大小
vue 复制代码
grid: {
  left: '10%',
    right: '10%',
    containLabel: true // 防止标签溢出
}
  • 动画配置
vue 复制代码
animation: true,          // 是否开启动画
  animationDuration: 1000   // 动画时长(ms)

动态更新

通过 setOption 更新配置时,可指定 notMerge: true 完全替换原有配置,或 lazyUpdate: true 延迟渲染。


完整示例

vue 复制代码
option = {
  title: { text: '销售数据' },
  tooltip: { trigger: 'axis' },
  legend: { data: ['销量', '库存'] },
  xAxis: {
    type: 'category',
      data: ['衬衫', '羊毛衫', '雪纺衫']
  },
  yAxis: { type: 'value' },
  series: [
    { name: '销量', type: 'bar', data: [5, 20, 36] },
    { name: '库存', type: 'line', data: [10, 25, 30] }
  ]
}

最佳实践

  1. 按需引入 :通过 echarts/core + 按需加载模块减小体积
  2. 类型验证 :使用 TypeScript 时配合 @types/echarts 获得类型提示
  3. 官方文档 :遇到具体配置项时,建议直接查阅 ECharts 官方配置手册

如果需要实现特定效果(如 3D 图表、地图可视化等),可进一步研究 echarts-gl 扩展和地图注册方法。

相关推荐
weixin_382395234 小时前
为小工厂量身打造:本地部署的物料管理系统带缺料计算
前端·制造
__zRainy__4 小时前
解决pnpm v10+不自动构建
前端·pnpm·工程化
猫猫不是喵喵.5 小时前
Vue3 Props 属性
前端·javascript·vue.js
醉城夜风~6 小时前
CSS元素显示模式(display)
前端·css
AI大模型-小华6 小时前
Codex 三方充值快速入门指南
java·前端·数据库·chatgpt·ai编程·codex·chatgpt pro
做前端的娜娜子9 小时前
同一链接实现 PC Web 与移动 H5 自适应
前端·掘金·金石计划
小帅不太帅9 小时前
架构没变、规模没变,DeepSeek V4 Flash 正式版凭什么暴涨 47 分?
前端·aigc·deepseek
jarvisuni9 小时前
DeepSeekFlash前端依旧拉垮,而且变慢了很多!
前端·javascript·算法
卷福同学10 小时前
AI编程出海第二步:验证关键词能否做站
前端·人工智能·后端