需求:
因为大屏基本从上午展示到晚上,不会频繁去打开页面。
前端实现:
在Vue的created钩子函数中发送初次请求,并使用JavaScript中的setInterval函数来设置整点定时发送请求。以下是一个示例
<template><div><h1>当前时间:{{ currentTime }}</h1><ul><li v-for="item in items" :key="item.id">{{ item.name }}</li></ul></div>
</template><script>
export default {data() {return {currentTime: new Date().toLocaleString(),items: []};},created() {// 初次请求this.fetchData();// 设置整点定时发送请求setInterval(() => {const now = new Date();// 获取分钟now.getMinutes() 获取秒数now.getSeconds()//一下为每日晚1点定时请求//一定要加秒if (now.getHours() === 1 && now.getSeconds()===0) {this.fetchData();}this.currentTime = now.toLocaleString();}, 1000);},methods: {fetchData() {// 发送请求的代码// 例如使用axios发送请求axios.get('/api/items').then(response => {this.items = response.data;});}}
};
</script>