自己写了一个vue轮播图,自己感觉还可以,但不怎么熟悉vue希望大神们能指出错误或不好的地方。效果:<template> <div class=“vuecarousel”> <div class=“contain” @mouseenter=“stop” @mouseleave=“start”> <ul class=“ul” :style="{width: imgs.length * 480 + ‘px’}"> //自适应宽度 <li class=“items” v-for="(img, index) in imgs" :key=“index” v-show=“index == showIndex”> <img :src=“img.src” alt=“轮播图”> </li> </ul> <ul class=“dots” :style="{width: imgs.length * 20 + ‘px’}"> //自适应宽度 <li v-for="(img, index) in imgs" :key=“index” :class=“index == showIndex ? ‘active’ : ‘’” @click=“showIndex = index”> // 点击下面的小圆点切换图片 </li> </ul> <div class=“control” v-show=“show”>// 点击两边的左右切换图片 <span class=“left” @click=“previous”><</span> // 上一张 <span class=“right” @click=“next”>></span> // 下一张 </div> </div> </div></template><script>export default { name: ‘VueCarousel’, created () { // 用钩子函数一开始就自动轮播 this.timer = setInterval(() => { this.next(); }, 2000) }, data(){ return { imgs:[ {src: require(’@/static/images/1.png’)}, {src: require(’@/static/images/2.png’)}, {src: require(’@/static/images/3.png’)}, {src: require(’@/static/images/4.png’)}, {src: require(’@/static/images/5.png’)} ], // 由于使用路径图片不显示,百度了一下用这种方法。把图片放在static里面还是出不来,如果有大神看到能否告知一二。 showIndex: 0, //显示第几个图片 timer: null, // 定时器 show: false // 前后按钮显示 } }, methods: { previous(){ // 上一张 if(this.showIndex <= 0){ this.showIndex = this.imgs.length - 1; }else{ this.showIndex –; } }, next () { // 下一张 if(this.showIndex >= this.imgs.length - 1){ this.showIndex = 0; }else{ this.showIndex ++; } }, start(){ //鼠标离开轮播区域时开始轮播 this.show = false; // 隐藏左右按钮 clearInterval(this.timer); this.timer = setInterval(() => { this.next(); }, 2000) }, stop () { //鼠标进入轮播区域时暂停轮播 this.show = true; // 显示左右按钮 clearInterval(this.timer); } }}</script><!– Add “scoped” attribute to limit CSS to this component only –><style scoped lang=“scss” scoped> // 第一次使用sass,又不好的地方请指出来.contain { position: relative; top: 50%; left: 50%; width: 480px; height: 302px; transition: all .8s; transform: translateX(-50%); color: #fff; overflow: hidden; cursor: pointer; .ul { height: 100%; list-style: none; .items { position: absolute; top: 0px; width: 100%; height: 100%; img { width: 100%; height: 100%; } } } .dots { position: absolute; left: 50%; bottom: 30px; height: 10px; transform: translateX(-50%); li { float: left; width: 10px; height: 10px; margin: 0px 5px; border-radius: 50%; transition: all .3s; background-color: antiquewhite; list-style: none; } .active { background-color: blue; } } .control { .left { position: absolute; top: 50%; left: 10px; padding: 5px; transform: translateY(-50%); font-size: 20px; cursor: pointer; &:hover { background-color: rgba($color: #000000, $alpha: 0.3); } } .right { position: absolute; top: 50%; right: 10px; padding: 5px; transform: translateY(-50%); font-size: 20px; cursor: pointer; &:hover { background-color: rgba($color: #000000, $alpha: 0.3); } } }}</style>