vue使用window.print()打印时echarts图表不显示

188 阅读1分钟

问题描述

前言:在原生html中使用window.print()来打印时echarts图表显示毫无问题,换到vue中来写就出现了在打印时echarts图表不显示的情况。

解决问题

<el-button type="primary" size="mini" @click="printBtn">打印报告</el-button>

<div class="printBox">
    <div class="content">
        <div class="tltPuble">营养状况</div>
        <div class="nutritionalStatus">
            <img :src="mainWeightIMG" id="mainWeight" style="width: 770px; height: 500px" />
        </div>
    </div>
<div>

<script>
import echarts from "echarts";
export default {
  name: 'EvaluatePrint',
  data() {
    return {
      mainWeightIMG: null,
    }
  },
  mounted() {
    this.innerWid()
  },
  methods: {
    innerWid() {
      var mainWeight = echarts.init(document.getElementById("mainWeight"));
    
      // 体重(kg)
      mainWeight.setOption({
        title: {
          text: "体重(%)",
        },
        xAxis: {
          type: "category",
          data: ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"],
        },
        yAxis: {
          type: "value",
        },
        series: [
          {
            data: [40, 42, 38, 45, 43, 42, 37],
            type: "line",
            animation: false,
            symbol: "circle", //将小圆点改成实心 不写symbol默认空心
            symbolSize: 6, //小圆点的大小
            label: {
              show: true,
              color: "##ED711F",
            },
            itemStyle: {
              color: "#ED711F", // 圆点背景色
            },
            lineStyle: {
              normal: {
                width: 1,
                color: "#ED711F",
              },
            },
            areaStyle: {
              normal: {
                //右,下,左,上
                color: new echarts.graphic.LinearGradient(
                  0,
                  0,
                  0,
                  1,
                  [
                    {
                      offset: 0,
                      color: "rgba(237, 113, 31, .1)",
                    },
                    {
                      offset: 1,
                      color: "#FFFFFF",
                    },
                  ],
                  false
                ),
              },
            },
          },
        ],
      });
      
      this.mainWeightIMG = mainWeight.getDataURL();
    },

    printBtn() { // 确认打印
      setTimeout(() => {
        const newstr = document.getElementsByClassName('printBox')[0].innerHTML;
        window.document.body.innerHTML = newstr;
        const oldstr = window.document.body.innerHTML;
        window.print();
        // 解决打印之后按钮失效问题
        window.location.reload();
        window.document.body.innerHTML = oldstr;
        return false;
      }, 200);
    }
  },
}
</script>

备注

知道问题所在的大佬可以在下面留言讲解一下