Vue——自动切换图片

发布时间 2023-06-03 08:57:13作者: 抱紧小洪

利用属性指令 + 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>