在vue中如何使用定时器去执行一个数组里的几个函数

直接上代码

<template>
    <div class="hello" style="position: relative">
        <div class="box1" v-show="box1"
             style="width: 100px;height: 100px;background: red;position:absolute; top: 0;left: 100px"></div>
        <div class="box2" v-show="box2"
             style="width: 100px;height: 100px;background: yellow;position:absolute; top: 0;left: 250px"></div>
        <div class="box3" v-show="box3"
             style="width: 100px;height: 100px;background: green;position:absolute; top: 0;left: 400px"></div>
        <div class="buttons_box" style="position: absolute;top: 150px;left: 180px">
            <button @click="box_1" class="active" ref="box_1">显示box1</button>
            <button @click="box_2" ref="box_2">显示box2</button>
            <button @click="box_3" ref="box_3">显示box3</button>
        </div>
    </div>
</template>

<script>
    export default {
        name: 'HelloWorld',
        data() {
            return {
                flag: 1,
                box1: true,
                box2: false,
                box3: false,
                timer: null
            }
        },
        methods: {
            box_1() {
                this.Clearn();
                this.$refs.box_3.className = '';
                this.box1 = true;
                this.box2 = false;
                this.box3 = false;
                this.flag = 2;
                this.$refs.box_1.className = 'active';
                this.Switch();

            },
            box_2() {
                this.Clearn();
                this.$refs.box_1.className = '',
                this.box1 = false;
                this.box2 = true;
                this.box3 = false;
                this.flag = 3;
                this.$refs.box_2.className = 'active';
                this.Switch();
            },
            box_3() {
                this.Clearn();
                this.$refs.box_2.className = '',
                this.box1 = false;
                this.box2 = false;
                this.box3 = true;
                this.flag = 1;
                this.$refs.box_3.className = 'active';
                this.Switch();
            },
            Switch() {
                this.timer = setInterval(() => {
                    if (this.flag == 1) {
                        this.box_1();
                    } else if (this.flag == 2) {
                        this.box_2();
                    } else {
                        this.box_3()
                    }
                }, 2000);
            },
            Clearn() {
                clearInterval(this.timer)
            },
        },
        created() {
            this.Switch();
        }
    }
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
    .active {
        background: #0a36e9;
        color: #fff;
    }
</style>
不足之处,请多指教
发布了6 篇原创文章 · 获赞 0 · 访问量 266

猜你喜欢

转载自blog.csdn.net/L863683305/article/details/103981473
今日推荐