VUE项目中使用Echarts以及setTimeout的一些要注意的点

本文介绍了如何在Vue项目中使用ECharts库,通过设置`Vue.prototype.$echarts`全局变量来方便地在组件中初始化图表。示例代码展示了如何在`mounted`钩子中初始化图表,并在`setTimeout`和`setInterval`中更新数据,实现实时数据变化的效果。同时,代码中详细解释了`setTimeout`和`setInterval`的用法以及在异步操作中保持`this`指向的技巧。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

vue使用echarts重点 main.js

import * as echarts from "echarts";
Vue.prototype.$echarts = echarts;

vue代码如下

//setTimeout内部this实际上是windows,所以如果内部需要使用data变量,需要把this保存起来当参数传进去
//setTimeout 第一个参数是函数体,如果是已定义好的函数就不需要加 function(){} 直接把函数名放进去
// 第二个参数是延迟时间(毫秒)
// 从第三个参数开始是要调用函数的参数,如果没有可以不填,如果需要传保存的this就用上了
<template>
  <div id="myChart" :style="{ width: '900px', height: '900px' }"></div>
</template>

<script>
import "echarts/lib/component/grid";
export default {
  data() {
    return {
      data: [],
      myChart: "",
      option: ""
    };
  },
  mounted() {
    this.init();
    let that = this;
    //setTimeout内部this实际上是windows,所以如果内部需要使用data变量,需要把this保存起来当参数传进去
    //setTimeout 第一个参数是函数体,如果是已定义好的函数就不需要加 function(){} 直接把函数名放进去
    // 第二个参数是延迟时间(毫秒)
    // 从第三个参数开始是要调用函数的参数,如果没有可以不填,如果需要传保存的this就用上了
    setTimeout(this.run, 3000, that);
    setInterval(this.run, 3000, that);
  },
  methods: {
    init() {
      this.myChart = this.$echarts.init(document.getElementById("myChart"));
      for (let i = 0; i < 5; ++i) {
        this.data.push(Math.round(Math.random() * 200));
      }
      console.log(this.data.length);
      this.myChart.setOption({
        xAxis: {
          max: "dataMax"
        },
        yAxis: {
          type: "category",
          data: ["A", "B", "C", "D", "E"],
          inverse: true,
          animationDuration: 300,
          animationDurationUpdate: 300,
          max: 2 // only the largest 3 bars will be displayed
        },
        series: [
          {
            realtimeSort: true,
            name: "X",
            type: "bar",
            data: this.data,
            label: {
              show: true,
              position: "right",
              valueAnimation: true
            }
          }
        ],
        legend: {
          show: true
        },
        animationDuration: 0,
        animationDurationUpdate: 3000,
        animationEasing: "linear",
        animationEasingUpdate: "linear"
      });
      // this.option = {};
    },
    run(that) {
      for (var i = 0; i < that.data.length; ++i) {
        if (Math.random() > 0.9) {
          that.data[i] += Math.round(Math.random() * 2000);
        } else {
          that.data[i] += Math.round(Math.random() * 200);
        }
      }
      that.myChart.setOption({
        series: [
          {
            type: "bar",
            data: that.data
          }
        ]
      });
    }
  }
};
</script>

<style></style>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值