vue制作简易轮播图

142 阅读1分钟

css样式

<style>
    * {
        margin: 0;
        padding: 0;
        list-style: none;
    }

    #app {
        position: relative;

    }

    ul {
        position: absolute;
        bottom: 10px;
        left: 220px;
    }

    li {
        width: 18px;
        height: 18px;
        border-radius: 10px;
        background-color: red;
        float: left;
        margin-right: 20px;

    }

    .active {
        background-color: blue;
    }
</style>

html内容

 <div id="app">
    <div class="content">
        <img :src="img" alt="" v-for="(img , i) in list" v-show="i===activeIndex">
        <ul class="indexes">
            <li :class="{active:i===activeIndex}" v-for="(img , i) in list" @click="change(i)" @mouseenter="hover(i)"></li>
        </ul>
    </div>
</div>

js内容

<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>

<script>
    let a = new Vue({
        el: "#app",
        data() {
            return {
                activeIndex: 0,
                list: [
                    "https://imgcps.jd.com/ling/2372749/6L-Q5Yqo5YGl6Lqr5oyH5Y2X/6JCl5YW76L-b6Zi256-H/p-5bd8253082acdd181d02fa0f/bfd5e4b9.jpg",
                    "https://img11.360buyimg.com/pop/s590x470_jfs/t1/106572/13/16926/96863/5e81b362E864b7c6c/c71f77c101eed8b2.jpg.webp",
                    "https://img30.360buyimg.com/pop/s590x470_jfs/t1/108867/16/10863/77524/5e83f328Eeb0922c6/6f6fc119f03c78f0.jpg.webp",
                    "https://img30.360buyimg.com/pop/s590x470_jfs/t1/129759/33/546/58234/5ece7096Ed023063f/65c76df588218f06.jpg.webp",
                ]
            }
        },
        mounted() {
            this.timer = setInterval(() => {
                        this.activeIndex++
                        if (this.activeIndex === this.list.length) {
                            this.activeIndex = 0
                        }
                    }, 1000);
        },
        methods: {
            run() {
                    this.timer = setInterval(() => {
                        this.activeIndex++
                        if (this.activeIndex === this.list.length) {
                            this.activeIndex = 0
                        }
                    }, 1000);
                },
                //
            change(i) {
                clearInterval(this.timer)
                this.activeIndex = i
                this.run()
            },
            hover(i){
                clearInterval(this.timer)
                this.activeIndex = i
                this.run()
            },

        },
    })
</script>