vue + js 滚动播放列表、定时抓取数据库数据

最近保卫处的老师找我给学校的显示屏滚动展示数据,遇到了一点值得记录的东西

现在的需求是这样:

  1. web页面直接投屏到显示屏,所以打开之后大概率没人管它
  2. 数据库的内容定时会更新,并且是一天可能要插入好几次数据
  3. 每页只展示六条数据,滚动播放

我的想法是:

  1. 设置一个定时事件,每次改变取到的列表,展示完前六条之后,将其移到后面,实现数据的滚动播放;当然这需要做一些判断,像数据有没有六条呀啥的
  2. 一开始想的是在设置一个定时器,这个时间大于第一个,然后定时从数据库取数据,但是 !!! 这样造成的问题就是如果在列表中的数据过多,那么就会造成每次数据还没滚动播放完就开始取新的数据,那么就会造成有些数据根本没展示的问题
  3. 对2的修改思路:改为每次滚动播放完列表数据后,再从数据库中重新取数据,刷新页面

代码如下:

part_1

# 前端部分,主要就是展示前六条数据
<div style="margin-top: 100px; text-align: center; font-weight: 700"> <ul style="width: 100%; font-size: 100px; color: white; text-align: left"> <li v-for="item in dataList.slice(0, 6)" style="display: block; width: 50%; float: left; list-style-type:none; margin-top: 50px"> {{ item.che }} </li> </ul> </div>

part_2

// 使用vm 、watch监听
vm = new Vue({ el: '#app', data() { return { dataList: [], date: '', len: 0, timer: '', } }, created() { this.getData(); // 1. 获取数据 }, mounted() { this.play(); // }, watch: { len: function () { this.$nextTick(function (){ console.log("this.timer: " + this.timer) if (this.timer != ''){ clearInterval(this.timer) }
          // +15000能在一开始this.len = 0时定时访问数据库,并且让切换更自然一点 let time
= 30000 * this.len / 6 + 15000 // 重新获取数据库的时间由数据播放长短决定 console.log(time) this.timer = setInterval(this.getData, time); }) } }, methods: { getData() { let that = this $.ajax({ url: "/getOverSpeed", dataType: 'json', type: "get", tranditional: true, success: function (response) { that.dataList = response['datas'] vm.len = that.dataList.length // !!! 监听dataList的长度变化、一旦改变就表示数据库有增删,那么就触发watch that.date = moment().format('YYYY-MM-DD') }, error: function () { alert("error") } }) }, play() { setInterval(this.change, 30000); // 数据滚动播放定时器,每六条停留30s }, change() { if(this.dataList.length > 6){ // 实现数据滚动 for (let i=0; i<6; i++){ this.dataList.push(this.dataList.shift()) } } } } }) </script>

当然,这样写肯定是效率不怎么高的,感觉前后端的负荷都很大

但我觉得这是一种不错的解决思路,所以记录记录嘿嘿~

posted @ 2021-04-26 21:09  swenw  阅读(713)  评论(0)    收藏  举报