利用属性指令 + setInterval(是一个实现定时调用的函数)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="js/vue.js"></script>
</head>
<body>
<div id="app">
<img v-bind:src="img[currentIndex]" alt="" @click="handleClick2">
<div>
<button @click="handleClick">点我切换</button>
</div>
</div>
</body>
<script>
var vm = new Vue({
el: '#app',
data: {
img: [
'img/1.png',
'img/2.png',
'img/3.png',
'img/4.png',
'img/5.png',
'img/6.png',
'img/7.png',
'img/8.png',
],
currentIndex: 0,
timer: null,
},
methods: {
handleClick() {
this.timer = setInterval(() => {
this.currentIndex = (this.currentIndex + 1) % this.img.length;
}, 1000);
},
handleClick2() {
clearInterval(this.timer);
},
},
})
</script>
</html>
补充延时任务和定时任务
setTimeout(function(){},3000) # 3s后执行匿名函数 延时任务
var t=setInterval(function(){},3000) # 每隔3s执行匿名函数 定时任务
clearInterval(t) # 停止定时任务
t=null