Vue.js 图片轮播:使用按钮切换图片
"<template>\n <div class="carousel">\n <img :src="currentImage" alt="carousel-image">\n <div class="controls">\n <button @click="prevImage">Previous</button>\n <button @click="nextImage">Next</button>\n </div>\n </div>\n</template>\n\n<script>\nexport default {\n data() {\n return {\n images: [\n 'image1.jpg',\n 'image2.jpg',\n 'image3.jpg',\n // 添加更多图片\n ],\n currentIndex: 0\n };\n },\n computed: {\n currentImage() {\n return require(@/assets/${this.images[this.currentIndex]});\n }\n },\n methods: {\n prevImage() {\n this.currentIndex = (this.currentIndex - 1 + this.images.length) % this.images.length;\n },\n nextImage() {\n this.currentIndex = (this.currentIndex + 1) % this.images.length;\n }\n }\n};\n</script>\n\n<style scoped>\n.carousel {\n position: relative;\n width: 500px;\n height: 300px;\n overflow: hidden;\n}\n\n.controls {\n position: absolute;\n bottom: 10px;\n left: 50%;\n transform: translateX(-50%);\n}\n\nbutton {\n margin: 0 10px;\n}\n</style>\n\n在上面的示例中,images数组包含了要轮播的图片的文件名。currentIndex用于跟踪当前显示的图片的索引。currentImage是一个计算属性,根据currentIndex返回当前显示的图片的路径。\n\nprevImage和nextImage方法分别用于切换到上一张和下一张图片。使用取模算法可以实现循环切换。\n\n在<template>中,使用<img>标签显示当前图片,并使用<button>作为切换按钮。轮播图容器使用.carousel样式设置宽度和高度,并使用.controls样式对切换按钮进行定位。\n\n请注意,这只是一个基本的示例,您可以根据需要自定义样式和添加更多功能。
原文地址: https://www.cveoy.top/t/topic/pD0F 著作权归作者所有。请勿转载和采集!