Echarts动态修改数据和添加样式

902 阅读1分钟

异步原因,使用v-if判断接口数据是否获得, Object.keys() 将对象的key合在一起返回一个数组。
<line-chart :reportList="reportList" v-if="Object.keys(reportList).length"></line-chart>

  created() {
    reportGet("reports/type/1")
      .then((res) => {
        let { meta, data } = res.data;
        if (meta.status == 200) {
          this.reportList = data;
        }else{
          this.$message.error(meta.msg);
        }
      })
      .catch((err) => {
        this.$message.error(err);
      });
  },
复制代码

图表组件

<script>
import * as echarts from "echarts";
export default {
  name: "LineChart",
  props: {
    reportList: {
      type: Object,
      // 接口数据没有获得时的默认值
      default: () => {
        return {
          title: {
            text: "折线图",
          },
          tooltip: {},
          xAxis: {
            axisLabel: {
              /* 显示所有的x轴的数据 */
              interval: 0,
              /* 放不下的倾斜角度 */
              rotate: 0,
              /* 数据距离刻度线的距离 */
              margin: 10,
            },
            data: ["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"],
          },
          yAxis: {},
          series: [
            {
              name: "销量",
              type: "line",
              data: [5, 20, 36, 10, 10, 20],
            },
          ],
        };
      },
    },
  },
  data() {
    return {
      lineList: {},
    };
  },
  mounted() {
    var myChart = echarts.init(document.getElementById("line"));
    this.lineList = JSON.parse(JSON.stringify(this.reportList));
    this.lineList.title = { text: "折线图" };
    this.lineList.grid = {
      width: "80%",
      left: "15%",
      // top:'30%'
    };
    // this.lineList.grid={};
    // this.lineList.grid.width='80%'
    // this.lineList.grid.left='20%'

    // x轴文字样式
    this.lineList.xAxis[0].axisLabel = {
      interval: 0,
      rotate: 30,
      margin: 10,
    };

    this.lineList.legend.top='10%'

    // 把折线图区域删除
    this.lineList.series.forEach(r => {
      delete r.areaStyle;
      // 线条圆润
      r.smooth=true
     
    });
    // 绘制图表
    myChart.setOption(this.lineList);
    window.LineChart = myChart;
  },
};
</script>