用Vue.js写一个轮播图格式
时间: 2024-03-07 09:47:52 浏览: 65
好的,以下是一个基于 Vue.js 的轮播图实现示例:
HTML 代码:
```html
<div id="app">
<div class="slider">
<transition-group name="fade" tag="ul">
<li v-for="(img, index) in imgs" :key="index" v-show="currentIndex === index">
<img :src="img">
</li>
</transition-group>
<div class="slider-nav">
<a v-for="(img, index) in imgs" :key="index" href="#" @click.prevent="show(index)"
:class="{ active: currentIndex === index }">{{ index + 1 }}</a>
</div>
</div>
</div>
```
CSS 代码:
```css
.slider {
position: relative;
overflow: hidden;
}
.slider ul {
list-style: none;
margin: 0;
padding: 0;
position: relative;
}
.slider ul li {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
opacity: 0;
transition: opacity 0.5s ease-in-out;
}
.slider ul li img {
width: 100%;
height: 100%;
object-fit: cover;
}
.slider-nav {
position: absolute;
bottom: 20px;
left: 50%;
transform: translateX(-50%);
text-align: center;
}
.slider-nav a {
display: inline-block;
width: 24px;
height: 24px;
line-height: 24px;
border-radius: 50%;
background-color: #ccc;
margin: 0 8px;
color: #fff;
text-align: center;
font-size: 14px;
text-decoration: none;
transition: background-color 0.5s ease-in-out;
}
.slider-nav a.active, .slider-nav a:hover {
background-color: #f60;
}
.fade-enter-active, .fade-leave-active {
transition: opacity 0.5s ease-in-out;
}
.fade-enter, .fade-leave-to {
opacity: 0;
}
```
JavaScript 代码:
```javascript
new Vue({
el: '#app',
data: {
imgs: [
'img1.jpg',
'img2.jpg',
'img3.jpg'
],
currentIndex: 0
},
methods: {
show: function(index) {
this.currentIndex = index;
},
showNext: function() {
this.currentIndex = (this.currentIndex + 1) % this.imgs.length;
}
},
mounted: function() {
// 自动播放
setInterval(this.showNext, 3000);
}
});
```
这个轮播图实现了自动播放、导航点击切换图片等功能,使用了 Vue.js 中的动态绑定和过渡效果。你可以替换 HTML 代码中的图片地址和 CSS 代码中的样式来适应你的需求。
阅读全文