<template>
<div class="random">
<span id="adopt">开始点名</span>
</div>
</template>
<script>
data () {
return {
list: [
{ name: '余光中', id: 1 },
{ name: '郑愁予', id: 2 },
{ name: '戴望舒', id: 3 },
{ name: '乐毅', id: 4 },
{ name: '吴起', id: 5 },
{ name: '孙膑', id: 6 },
{ name: '庞涓', id: 7 },
{ name: '周树人', id: 8 },
{ name: '王语嫣', id: 9 },
{ name: '木婉清', id: 10 },
{ name: '程灵素', id: 11 },
{ name: '周芷若', id: 12 },
{ name: '凌霜华', id: 13 },
{ name: '任盈盈', id: 14 },
{ name: '纪晓芙', id: 15 },
{ name: '廉颇', id: 16 },
{ name: '赵牧', id: 17 },
{ name: '赵奢', id: 18 },
{ name: '赵括', id: 19 },
{ name: '项燕', id: 20 }
],
timer: null,
classId: null
};
},
//开始 (我这里是在父组件 调用此方法)
parentHandleclick () {
const adopt = document.getElementById('adopt');
const goods = this.list;
const length = this.list.length - 1;
this.timer = setInterval(function () {
const str = Math.floor(Math.random() * (length - 0 + 1)) + 0;
if (goods[str]) {
adopt.innerText = goods[str].name;
adopt.setAttribute('data-id', goods[str].id);
}
}, 70);
setTimeout(this.stop, 3000); // 这里设置的是 三秒后自动停止
},
// 停止
stop () {
const adopt = document.getElementById('adopt');
console.log(adopt.innerText, adopt.getAttribute('data-id'));
clearInterval(this.timer);
}
![在这里插入图片描述](https://img-blog.csdnimg.cn/20210114114118265.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L1lvZ2E5OQ==,size_16,color_FFFFFF,t_70)