虽然可以直接用别人造好的轮子,但内心其实是有点想自己用Vue写一个(虽然我是React技术栈的)。这样子的话,具体的细节点就可以做到根据需求进行完美的调整啦。
Vue的官网已经了封装组件 <transition-group> ,所以写起来其实感觉简单了许多。
初步
下面的是初步完成需求基础版且复用性不高的代码。
<div id='carousel'>
<Carousel :urls="['./images/one.png','./images/two.png','./images/three.png']"> </Carousel>
</div>
Vue.component('Carousel', {
props: { urls: Array },
data: function () {
return {
style: [
{
width: "590px",
left: "-160px",
top: "50px",
zIndex: 2,
position: 'absolute',
transition: 'all 1s',
},
{
width: "760px",
zIndex: 3,
left: "0px",
top: "0px",
position: 'absolute',
transition: 'all 1s',
},
{
width: "590px",
left: "330px",
top: "50px",
zIndex: 2,
position: 'absolute',
transition: 'all 1s',
}
],
previous: 0,
now: Date.now()
}
},
methods: {
switchLeft: function () {
//向左切换
this.now = Date.now();
if (this.now - this.previous > 1000) {
this.style.push(this.style.shift());
this.previous = this.now;
}
},
switchRight: function () {
//向右切换
this.now = Date.now();
if (this.now - this.previous > 1000) {
this.style.unshift(this.style.pop());
this.previous = this.now;
}
}
},
template: `
<div>
<transition-group
name="carousel"
tag="ul"
>
<li v-for="(item, index) in urls" :key="item" :style="style[index]">
<img :src="item" >
</li>
</transition-group>
<span class='left' @click="switchLeft"> <span class="arrows"></span></span>
<span class='right' @click="switchRight"> <span class="arrows"></span></span>
</div>
`,
})
#carousel ul {
position : relative;
width : 760px;
margin : auto;
transform: translateY(50%);
list-style: none;
}
#carousel li img {
width: 100%;
box-shadow: 0px 20px 20px 0px rgba(0, 0, 0, 0.1);
}
.left,
.right {
width : 64px;
height : 64px;
background : rgba(189, 197, 205, 0.4);
border-radius : 50%;
position : absolute;
right : 10%;
display : flex;
justify-content: center;
align-items : center;
top : 50%;
transform : translateY(-50%);
cursor : pointer;
}
.left {
left: 10%;
}
.right {
right: 10%;
}
.left .arrows,
.right .arrows {
width : 15px;
height : 15px;
border : 4px solid #fff;
transform: rotate(45deg);
}
.left .arrows {
border-top-color : transparent;
border-right-color: transparent;
margin-left : 10px;
}
.right .arrows {
border-bottom-color: transparent;
border-left-color : transparent;
margin-right : 10px;
top : 50%;
}
失败的更改成配置项的过程
在优化的过程中,发现了想要在transition-group组件中加入动态的style去控制宽度,是做不到的。(这个不是必须的,只是明白了而已)
要更改为配置项,那么之前的style数组就应该是根据图片数量自动生成的。但在created时期生成数据或者直接computed时候生成数据,都出现了更新数据,视图都没有更新的情况,应该是我对vue没有深入过,导致没有理解到其原理。以后有机会再做。
网友评论