vue+echarts 从后台获取数据设置折线图

1,211 阅读1分钟
<el-col :span="8">
    <el-card shadow="always">
      <line-chart :optionsReports="optionsReports" v-if="Object.keys(optionsReports).length"/>
    </el-card>
</el-col>
<template>
  <div class="line-chart">
    <div id="main" ref="main"></div>
  </div>
</template>

<script>
import * as echarts from "echarts";
export default {
  name: "LineChart",
  data(){
    return {
      options:{}
    }
  },
  props: {
    optionsReports: {
      type: Object,
      default: () => {
        return {
          title: {
            text: "折线图",
          },
          tooltip: {},
          xAxis: {
            data: ["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"],
            axisLabel: {
              /* 显示所有的x轴的数据 */
              interval: 0,
              /* 放不下的倾斜角度 */
              rotate: 15,
              /* 数据距离刻度线的距离 */
              margin: 15,
            },
          },
          yAxis: {},
          series: [
            {
              name: "销量",
              type: "line",
              data: [5, 20, 36, 10, 10, 20],
            },
          ],
        };
      },
    },
  },
  mounted() {
    // 基于准备好的dom,初始化echarts实例
    // var myChart = echarts.init(document.getElementById("main"));
    var myChart = echarts.init(this.$refs.main);
    // 深拷贝组件内使用变量存储父组件传递的数据
    this.options = JSON.parse( JSON.stringify(this.optionsReports) );
    console.log(this.options);
    // 设置标题
    this.options.title = {
      text: "折线图"
    }
    // 设置图标的大小与位置
    this.options.grid = {
      width: '80%',
      left:'20%',
      top:'30%'
    }
    // 调整图例组件距离顶部的距离
    this.options.legend.top = '10%'
    // 设置提示框显示与位置
    this.options.tooltip = { 
      show:true,
      position:'inside'
    }
    // x轴刻度文本设置
    this.options.xAxis[0].axisLabel = {
      interval: 0,             
      rotate: 15,
      margin: 15,
    }
    // 设置x轴刻度线与标签对齐
    this.options.xAxis[0].axisTick = {
      alignWithLabel: true
    }
    // 显示y轴轴线
    this.options.yAxis[0].axisLine = {
      show:true
    }
    this.options.series.forEach(r => {
      // 去除区域面积图
      delete r.areaStyle
      // 曲线平滑选项
      r.smooth = true
    });
    // 绘制图表
    myChart.setOption(this.options);
    window.LineChart = myChart;
  },
};
</script>

<style scoped lang="scss">
#main {
  height: 300px;
}
</style>