前几天,发现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}`);
});