前端做的轮询小案例- 结合vue2 + nodejs

前几天,发现ui给了一个消息的按钮,然后就想到了做一个轮询解决消息试试更新.

其实在前端眼里,轮询第一次听说,或者第一次听 心跳机制, 总结一下: 不管使用什么技术,总的来说就是想让用户能实时的看到消息.而不是刷新页面来看.

总其原理很简单: 就是让项目每隔一段时间做一个异步的请求,来更新消息的按钮图标.

上代码:

前端代码:

 

<template>  
  <div>  
    <h1>轮询示例</h1>  
    <p v-if="pollingData">上次轮询时间: {{ pollingData.timestamp }}</p>  
    <p v-if="pollingData">消息: {{ pollingData.message }}</p>  
    <button @click="startPolling">开始轮询</button>  
    <button @click="stopPolling">停止轮询</button>  
  </div>  
</template>  
  
<script>  
import axios from 'axios';  
  
export default {  
  data() {  
    return {  
      pollingData: null,  
      pollingInterval: null  
    };  
  },  
  methods: {  
    async fetchData() {  
      try {  
        const response = await axios.get('http://localhost:3000/poll');  
        this.pollingData = response.data;  
      } catch (error) {  
        console.error(error);  
      }  
    },  
    startPolling() {  
      if (this.pollingInterval) {  
        return;  
      }  
      this.pollingInterval = setInterval(this.fetchData, 2000); // 每2秒轮询一次  
      this.fetchData(); // 立即执行一次  
    },  
    stopPolling() {  
      clearInterval(this.pollingInterval);  
      this.pollingInterval = null;  
    }  
  },  
  mounted() {  
    // 在这里可以根据需要自动开始轮询  
  }  
};  
</script>

  这个是编写了一个按钮,实现开始轮询和停止轮询,  当轮询开启之后,确实很让服务器压力变大,项目整体的性能降低,但是用户有看不到,他们都以为是网络卡,所以没有必要在意这些,主要能不刷新的情况下获取消息信息那就解决问题了

node服务器代码:

// server.js  
const express = require('express');  
const app = express();  
const port = 3000;  
  
app.get('/poll', (req, res) => {  
  // 模拟从数据库或其他服务获取数据  
  const data = {  
    timestamp: new Date().toISOString(),  
    message: '这是轮询返回的数据'  
  };  
  res.json(data);  
});  
  
app.listen(port, () => {  
  console.log(`Server is running on port ${port}`);  
});

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值