<template> <div v-chartResize style="width: 100%; height:600px;" ref="main"></div></template><script setup>import { ref, shallowRef, onMounted, onUnmounted, nextTick } from 'vue' // vue 内置方法import * as echarts from 'echarts/core' // echarts 图表// 定义响应式数据const main = ref(null)const state = shallowRef({ myChart: null, // echarts 图表})// 组件挂载后,此方法执行后,页面显示onMounted(() => { nextTick(() => { initChart() })})// 初始化 echartsconst initChart = () => { const colors = ['#5470c6', '#91cc75', '#fac858', '#ee6666', '#73c0de', '#3ba272', '#fc8452', '#9a60b4', '#ea7ccc'] state.myChart = echarts.init(main.value) state.myChart.setOption({ title: { // 标题组件,包含主标题和副标题 text: '柱状图', // 主标题文本 textStyle: { // 主标题文字参数设置 width: 500, // 文本显示宽度 color: '#0095e1', // 主标题文字的颜色 fontSize: 18, // 主标题文字的字体大小 }, subtext: '生活费用', // 副标题文本 subtextStyle: { // 副标题文字参数设置 color: '#000', // 副标题文字的颜色 }, itemGap: 10, // 主副标题之间的间距 x: 'left', // 主副标题x轴对齐方式 y: 'top', // 主副标题y轴对齐方式 }, legend: {}, // 图例组件展现了不同系列的标记 tooltip: { // 鼠标滑入提示框 trigger: 'axis', // 触发类型 axisPointer: { // 坐标轴指示器配置项 type: 'shadow' // 指示器类型 } }, grid: { // 直角坐标系内绘图网格,类似padding top: '15%', left: '3%', right: '4%', bottom: '3%', containLabel: true, // grid 区域是否包含坐标轴的刻度标签 }, xAxis: { // 直角坐标系 grid 中的 x 轴 type: 'category', data: ['星期一', '星期二', '星期三', '星期四', '星期五', '星期六', '星期日'] }, yAxis: [ // 直角坐标系 grid 中的 y 轴 { type: 'value', // 坐标轴类型 name: '人民币', // 坐标轴名称 position: 'left', // y 轴的位置 alignTicks: true, // 在多个 y 轴为数值轴的时候,可以开启该配置项自动对齐刻度 axisLine: { // 坐标轴轴线相关设置 show: true, lineStyle: { color: colors[0] } }, axisLabel: { // 坐标轴刻度标签的相关设置 formatter: '{value} ¥' } }, { type: 'value', name: '美元', position: 'right', alignTicks: true, axisLine: { show: true, lineStyle: { color: colors[0] } }, axisLabel: { formatter: '{value} $' } }, ], series: [ { type: 'bar', // echarts 图表类型 name: '美杜莎', // 系列名称,用于tooltip的显示 color: '#0095e1', // 调色盘颜色列表 data: [120, { // 定义单个柱子颜色 value: 200, itemStyle: { color: '#F56C6C' } }, 150, 80, 70, 110, 130], // 系列中的数据内容数组。数组项通常为具体的数据项 showBackground: true, // 是否显示柱条的背景色 backgroundStyle: { // 柱条的背景颜色 color: 'rgba(180, 180, 180, 0.2)' }, }, { type: 'bar', // echarts 图表类型 name: '焰灵姬', // 系列名称,用于tooltip的显示 data: [20, { // 定义单个柱子颜色 value: 300, itemStyle: { color: '#F56C6C' } }, 40, 60, 170, 210, 230], // 系列中的数据内容数组。数组项通常为具体的数据项 showBackground: true, // 是否显示柱条的背景色 backgroundStyle: { // 柱条的背景颜色 color: 'rgba(180, 180, 180, 0.2)' } }, { type: 'line', // echarts 图表类型 name: '云韵', // 系列名称,用于tooltip的显示 data: [20, 100, 10, 180, 120, 200, 300], // 系列中的数据内容数组。数组项通常为具体的数据项 showBackground: true, // 是否显示柱条的背景色 backgroundStyle: { // 柱条的背景颜色 color: 'rgba(180, 180, 180, 0.2)' }, yAxisIndex: 1, // 对应 yAxis 下标为 1 的轴 } ] })}// 组件销毁完成后执行的函数onUnmounted(() => { if (!state.myChart) { return } state.myChart.dispose() state.myChart = null})</script><style lang='scss' scoped></style>