目录
涉及内容:
随机函数 Math.random()
定时器 setInterval(函数名:时间(单位毫秒))
效果展示:![](https://img-blog.csdnimg.cn/e01742b021aa4248a1851812592a2688.gif)
代码实现
<style>
/* 展示的div的样式 */
.area {
height: 200px;
width: 200px;
background-color: yellow;
line-height: 200px;
color: green;
}
</style>
<!-- 绑定下面的vm模型 -->
<div class="container " id="redom_number">
<!-- 用<center>标签让按钮和文字居中 -->
<center>
<div class="area h1" >{{div_cover}}</div>
<!-- 开始按钮绑定定时器 -->
<button class="btn btn-primary " @click="start()"> 开始</button>
<!-- 结束按钮清楚定时器 -->
<button class="btn btn-danger" @click="end()"> 结束</button>
</center>
</div>
<script>
// 写出vm模型绑定上面的div
vm = new Vue({
el: "#redom_number",
// 写入数据
data: {
// 封面的数据
div_cover: '开始点名',
// 装定时器的容器
timer:null,
// 需要随机的列表(用索引提数据)
list_one: ['李一',
'屈二 ', '谢三 ', '张四 ', '曹五 ', '常六 ', '杜七 ', '高八 ',
'高九 ', '郭十 ', '韩十一 ', '胡十二 ', '李十三 ', '李十四 ', '李十五 ',
'李十六 ', '刘十七 ', '刘十八 ', '马十九 ','牛二十 ','申二一 ',
'宋二二 ','王二三 ','吴二四 ','叶二五 ',
'张二六 ','张二七 ','张二八 ','赵二九 ','赵三十 ','丁三一 ',
'杜三二 ','李三三 ','皮三四 ','王三五 ','王三六 ','夏三七 ',
'张三八 '
]
},
methods: {
// 给开始按钮绑定定时器
// 调用了Math.deadom()函数产生随机效果
start(){
clearInterval(this.timer)
this.timer=setInterval(function(){
// 随机数生成后*需要循环列表的长度使列表内都能随机提出
index=parseInt(Math.random()*vm.$data.list_one.length)
// 把随机的数据传输给页面
vm.$data.div_cover=vm.$data.list_one[index]
// 定时器100毫秒(0.1秒)调用随机函数一次
},100)
},
// 点击结束按钮清空定时器
end(){
clearInterval(this.timer)
}
}
})
</script>