Vue3 单页面引入Echarts以及自适应屏幕大小

5,748 阅读1分钟

安装echarts指令

npm install echarts --save

template 写入div标签

<template>
    // Vue3 是不需要在template下包裹标签的 但是避免Vue2报错还是包裹了
    <div>
        <div id="myChart" :style="{ width: '100%', height: '300px' }"></div>
    </div>
<template>

Vue3 setup下使用echarts

<script setup>
import * as echarts from "echarts";
onMounted(() => {
  // 这里是由于图表渲染快于父元素导致图表比例溢出,做的一个延缓操作
  setTimeout(() => {
    line();
  }, 1000);
});

const line = () => {
  let myChart = echarts.init(document.getElementById("myChart"));
  myChart.setOption({
    xAxis: {
      type: "category",
      data: ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"],
    },
    yAxis: {
      type: "value",
    },
    series: [
      {
        data: [150, 230, 224, 218, 135, 147, 260],
        type: "line",
      },
    ],
  });
  window.onresize = function () {
    //自适应大小, 不用的话不会自适应大小。
    myChart.resize();
  };
};
</script>

image.png