vue2使用websocket和echars动态展示本机CPU使用情况,后端框架使用fastapi

后端代码:

from fastapi import FastAPI, WebSocket
import psutil
import asyncio

app = FastAPI()

@app.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
    await websocket.accept()
    while True:
        cpu_usage = psutil.cpu_percent(interval=1)  # 获取 CPU 使用率
        await websocket.send_json({
   "cpu_usage": cpu_usage})
        await asyncio.sleep(1)  # 每秒发送一次数据

后端运行:
uvicorn main:app --port 9999

前端代码:

安装插件
npm install echarts

<template>
  <div>
    <div id="cpu-chart" style="width: 600px;height:400px;"></div>
  </div>
</template>

<script>
import * as echarts from 'echarts';

export default {
  data() {
    return {
      chart: null,
      ws: null,
      data: [],
    };
  },
  mounted() {
    this.initWebSocket();
    this.initChart();
  },
  methods: {
    initWebSocket() {
      this.ws = new WebSocket('ws://localhost:9999/ws');
      this.ws.onmessage = (event) => {
        const message = JSON.parse(event.data);
        this.updateChartData(message.cpu_usage);
      };
    },
    initChart() {
      this.chart = echarts.init(document.getElementById('cpu-chart'));
      const option = {
        title: {
          text: 'CPU Usage',
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
          },
        },
        xAxis: {
          type: 'category',
          data: [],
        },
        yAxis: {
          type: 'value',
          min: 0,
          max: 100,
          axisLabel: {
            formatter: '{value} %',
          },
        },
        series: [
          {
            name: 'CPU Usage',
            type: 'line',
            data: this.data,
          },
        ],
      };
      this.chart.setOption(option);
    },
    updateChartData(cpuUsage) {
      const now = new Date();
      const time = `${now.getHours()}:${now.getMinutes()}:${now.getSeconds()}`;
      this.data.push(cpuUsage);
      this.chart.setOption({
        xAxis: {
          data: [...Array(this.data.length).keys()].map(i => `#${i + 1}`),
        },
        series: [{
          data: this.data,
        }],
      });
    },
  },
  beforeDestroy() {
    if (this.ws) {
      this.ws.close();
    }
  },
};
</script>

<style>
/* Your CSS here */
</style>

相关推荐

  1. 使用Vue+ ECharts进行动态图表展示

    2024-01-26 12:42:05       32 阅读
  2. Vue3使用component动态展示组件

    2024-01-26 12:42:05       8 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-01-26 12:42:05       16 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-01-26 12:42:05       16 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-01-26 12:42:05       15 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-01-26 12:42:05       18 阅读

热门阅读

  1. Backend - Django URL 路由 & 重定向 & url编码解码

    2024-01-26 12:42:05       34 阅读
  2. CentOS 7 部署 MiniKube

    2024-01-26 12:42:05       40 阅读
  3. (3)Elastix图像配准:项目实战(2D / 3D)

    2024-01-26 12:42:05       34 阅读
  4. 第30章群,环,域

    2024-01-26 12:42:05       30 阅读
  5. webRtc常用的方法

    2024-01-26 12:42:05       27 阅读
  6. 【owt】webrtc的随机数生成

    2024-01-26 12:42:05       29 阅读
  7. node多版本管理使用npm失败的方法

    2024-01-26 12:42:05       38 阅读
  8. ·状态模式

    2024-01-26 12:42:05       40 阅读
  9. JVM内存模型解析

    2024-01-26 12:42:05       27 阅读
  10. Ubuntu20.04

    2024-01-26 12:42:05       29 阅读