JavaScript-自制列表自动滚动[Vue][v-for]
1. 实现思路
- 假设有一个数据源列表:rows数组;
- 再定义一个用于最终被v-for循环生成列表的数据源列表:toShowRows数组;
- 现在只需让toShowRows首元素弹出,然后再从尾部加入一个新元素,此时由于Vue的响应式,就会更新列表;
- 最后,设置自我递归调用的setTimeout定时器,对上述环节每隔一定时间执行一次,即可达到列表向上自动滚动的效果!
2.完整HTML文件代码
<!DOCTYPE html>
<html lang="zh">
<head>
<meta http-equiv="Content-Type" charset=UTF-8">
<style>
.row{
display: flex;
flex-direction: row;
}
.order-div{
width: 30%;
height: 100%;
background-color: aquamarine;
}
.item-div{
width: 30%;
height: 100%;
background-color: blanchedalmond;
}
.message-div{
width: 40%;
height: 100%;
background-color: tomato;
color:white;
}
</style>
</head>
<body>
<div id="app">
<div class="row" v-for="(item,index) in toShowRows" :style="`width:600px;margin:3px;border:${item} 3px solid;`">
<div class="order-div">{{rows.indexOf(item)}}</div>
<div class="item-div">{{item}}</div>
<div class="message-div">{{`border:${item} 3px solid;`}}</div>
</div>
</div>
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
<script>
const {createApp} = Vue;
createApp({
data() {
return {
message: 'Hello Vue!',
rows:['skyblue','orange','black','red','green','blue','yellow','#bfa','purple','#bce'],
toShowRows:[],
record:0
}
},
mounted(){
console.log('ok')
const timego = ()=>{
setTimeout(()=>{
if(this.toShowRows.length < this.rows.length){
this.toShowRows.push(this.rows[this.record++]);
}else{
console.log(this.record,'<==========');
this.toShowRows.shift();
if(this.record == this.rows.length){
this.record = 0;
console.log(this.record,'!==========');
}
this.toShowRows.push(this.rows[this.record++]);
}
timego()
}
,700
)
}
timego();
}
}).mount('#app')
</script>
</body>
</html>
3.自动滚动运行效果(gif)
![在这里插入图片描述](https://img-blog.csdnimg.cn/19762b6ee3704b2b8df9d9c8b5c817fd.gif#pic_center)