Dynamically set the height of the echarts chart in vue3

Dynamically set the height of the echarts chart in vue3

I recently wrote a vue3 project, and I had to use echarts graphics in the middle. Because I had to adapt to different monitors, I was almost going crazy. I have dealt with this problem countless times, but I encounter it every time. Let me record the solution this time.

1. Writing in components

You only need to write the html tag in the component, and then add the JavaScript code

<el-card class="top-graph" ref="topGra">
	<div style="height: 100%;" ref="speed"></div>
</el-card>

I won’t write the style. The outer layer is an el-card in elementplus, and the inner layer is the speed curve to be rendered.

Relevant code in js:

import {
    
     ref, reactive, onMounted, watch, nextTick } from 'vue'
import {
    
     useElementSize } from '@vueuse/core'  // 使用vueuse获取dom元素的尺寸

// 点击表格中的眼睛图标时,改变右侧顶部的数据,需要一个索引
const dataIndex = ref(0)
onMounted(() => {
    
    
    nextTick(() => {
    
    
        drawChart(dataIndex.value, speed.value)
    })

})

import {
    
     drawChart } from './components/LineChartOptions'
const speed = ref(null)
const topGra = ref(null)

const {
    
     width, height } = useElementSize(topGra)
console.log(width.value, height)


watch(() => [dataIndex, height], (newVal, oldVal) => {
    
    
    console.log(newVal)
    // currentHeight.value = newVal
    drawChart(newVal[0].value, speed.value, newVal[1].value)
}, {
    
     deep: true })

There is a bit of complicated logic here. The echarts chart changes. The loaded data source needs to be switched based on the responsive data of dataIndex. At the same time, the height of the displayed chart must be adaptive.

Implemented logic: monitor changes in the two values ​​of dataIndex and height. When changes occur, redraw the curve. It is best to add depth monitoring, that is, { deep: true }

So to get the height of the echarts diagram, useElementSize in the vueuse plug-in is used, which can get the height and width of the dom element. Note that it gets the height of the parent node of the echarts diagram, because echarts is difficult to do when there is no picture. , the node is not rendered at all, and the speed dom element cannot be obtained at all, so it can only be given a parent element and display the image by setting the same height as the parent element.

This is roughly the process, but it will be easier to understand based on the actual project.

In addition, you can see that drawChartI encapsulated this method in the plug-in. You can see how my plug-in is written< /span>

2. Writing method in plug-in

import axios from "axios";
import * as echarts from 'echarts'
export const drawChart = (index, ref, height=260) => {
    
    
  axios
    .get("static/json/speed.json")
    .then((res) => {
    
    
      const all_data = res.data[index];
      // console.log(all_data)
      const x = [];
      const data = [];
      for (let i = 0; i < all_data.length; i++) {
    
    
        x.push(all_data[i].time);
        // const {sgqs, swrs, ssrs} = all_data[i]
        // const datai = {sgqs, swrs, ssrs}
        const datai = {
    
     纵向速度: all_data[i].speed };
        data.push(datai);
      }

      const keyArray = Object.keys(data[0]);
      const series = [];
      keyArray.forEach((key) => {
    
    
        series.push({
    
    
          name: key,
          data: data.map((item) => item[key]),
          type: "line",
          smooth: true,
        });
      });
      // console.log(series)

      const options = {
    
    
        title: {
    
     text: "车辆速度变化情况" },
        tooltip: {
    
    
          // 鼠标悬浮提示框显示 X和Y 轴数据
          trigger: "axis",
          backgroundColor: "rgba(32, 33, 36,.7)",
          borderColor: "rgba(32, 33, 36,0.20)",
          // borderWidth: 1,
          textStyle: {
    
    
            // 文字提示样式
            color: "#fff",
            fontSize: "12",
          },
          axisPointer: {
    
    
            // 坐标轴虚线
            type: "cross",
            label: {
    
    
              backgroundColor: "#6a7985",
            },
          },
        },
        xAxis: {
    
    
          data: x,
          type: "category",
        },
        yAxis: {
    
    },
        legend: {
    
    
          data: keyArray,
        },
        series,
      };
      const chart_line = echarts.init(ref);
      chart_line.resize({
    
    height})
      chart_line.setOption(options);
      window.addEventListener("resize", () => {
    
    
        chart_line.resize();
      });
    })
    .catch((err) => {
    
    
      console.log(err);
    });
};

drawChart requires three parameters, data index, DOM to display the image, and the height of the image

These three elements are all passed by the component, but the height has a default value, which is 260px, but it will change according to your actual window size, because the height of my el-card also changes.

This method does the following:

  1. axios gets data
  2. Get the required data based on the index value (in fact, this should be done by the backend)
  3. Process the data required by echarts
  4. Initialize dom according to the input dom parameters
  5. Set the height of the figure according to the input height
  6. echarts settings option
  7. Monitor window changes and change window size

3. Several questions

In fact, according to the above solution, it has been roughly solved, but there are still a few small problems.

  1. When redrawing, the console will alert that there are pictures on the original dom, so before each redraw, you should actually determine whether the dom exists.
  2. When resizing in step 7 of the plug-in, no parameters are given.

Guess you like

Origin blog.csdn.net/u012848304/article/details/131892343