<script setup lang="ts"> import { reactive, ref, onMounted } from 'vue'; import * as echarts from 'echarts'; type EChartsOption = echarts.EChartsOption; type ECharts = echarts.ECharts; const colors = ['#9EB23B', '#EF9F9F']; const dynamicRef = ref<any>(null); const state = reactive({ app: {} as any, categories: null as any, categories2: null as any, data: [] as number[], data2: [] as number[], }); onMounted(() => { getCategories(); getCategories2(); getData(); getData2(); getChart(); }); var dynamicChart: ECharts; function getChart() { if (dynamicChart != null && dynamicChart != undefined) { dynamicChart.dispose(); } dynamicChart = echarts.init(dynamicRef.value); let option: EChartsOption; option = { color: colors, tooltip: { trigger: 'axis', axisPointer: { type: 'cross', }, }, legend: {}, dataZoom: { show: false, start: 0, end: 100, }, xAxis: [ { type: 'category', boundaryGap: true, data: state.categories, }, { type: 'category', boundaryGap: true, data: state.categories2, }, ], yAxis: [ { type: 'value', scale: true, name: '折线图', max: 30, min: 0, boundaryGap: [0.2, 0.2], axisLine: { show: true, lineStyle: { color: colors[0], }, }, }, { type: 'value', scale: true, name: '柱状图', max: 1200, min: 0, boundaryGap: [0.2, 0.2], axisLine: { show: true, lineStyle: { color: colors[1], }, }, }, ], series: [ { name: '折线图', type: 'line', data: state.data2, itemStyle: { color: colors[0], }, }, { name: '柱状图', type: 'bar', // 使用的 x 轴的 index,在单个图表实例中存在多个 x 轴的时候有用。 xAxisIndex: 1, yAxisIndex: 1, data: state.data, barWidth: 35, itemStyle: { borderRadius: 10, color: colors[1], }, }, ], }; state.app.count = 11; setInterval(function () { let axisData = new Date().toLocaleTimeString().replace(/^\D*/, ''); state.data.shift(); state.data.push(Math.round(Math.random() * 1000)); state.data2.shift(); state.data2.push(+(Math.random() * 10 + 5).toFixed(1)); state.categories.shift(); state.categories.push(axisData); state.categories2.shift(); state.categories2.push(state.app.count++); dynamicChart.setOption<EChartsOption>({ xAxis: [ { data: state.categories, }, { data: state.categories2, }, ], series: [ { data: state.data2, }, { data: state.data, }, ], }); }, 2100); option && dynamicChart.setOption(option); } function getCategories() { let now = new Date(); let res = <any>[]; let len = 10; while (len--) { res.unshift(now.toLocaleTimeString().replace(/^\D*/, '')); now = new Date(+now - 2000); } state.categories = res; } function getCategories2() { let res = []; let len = 10; while (len--) { res.push(10 - len - 1); } state.categories2 = res; } function getData() { let res = []; let len = 10; while (len--) { res.push(Math.round(Math.random() * 1000)); } state.data = res; } function getData2() { let res = []; let len = 0; while (len < 10) { res.push(+(Math.random() * 10 + 5).toFixed(1)); len++; } state.data2 = res; } </script> <template> <div class="fit" ref="dynamicRef"></div> </template> <style lang="scss" scoped></style>