这一节主要说一下如何复用翻牌器
效果如下:
$parent
this.$parent 可以访问到父组件 上所有的 data(){ 里的数据信息和生命周期方法,methods里的方法 }!
setTimeout(() => {
this.$parent.timedRefresh(this.userData, "user");
}, 1000);
在Home.vue页面
// 设置文字滚动
setNumberTransform(item) {
const numberItems = document.querySelectorAll(`.${item.id} i`);
// const numberItems = this.$refs[`${item.id}`]
const numberArr = item.valueArr.filter((item) => !isNaN(item));
numberItems.forEach((t) => {
t.style.transition = "transform 0s ease-in-out";
t.style.transform = `translateY(-0%)`;
});
setTimeout(() => {
numberItems.forEach((ls, index) => {
ls.style.transition = "transform 0.8s ease-in-out";
ls.style.transform = `translateY(-${numberArr[index] * 10}%)`;
});
}, 15);
},
// 定时
initInterval (targetList, time) {
const { setNumberTransform } = this
return setInterval((function fn(){
targetList.forEach(t => {
setTimeout(() => {
setNumberTransform(t)
}, 50)
})
return fn
})(), time)
},
// 刷新数字翻牌器
timedRefresh(targetList, type) {
let cityTimer;
let userTimer;
let deviceTimer;
if (type === "city") {
console.log('======')
console.log(targetList)
cityTimer = this.initInterval(targetList, 1000);
} else if (type === 'user') {
console.log('======')
console.log(targetList)
userTimer = this.initInterval(targetList, 5000)
}
if (type === 'device') {
console.log('------------------');
console.log(targetList);
deviceTimer = this.initInterval(targetList, 8000)
}
this.$once("hook:beforeDestroy", () => {
clearInterval(cityTimer);
clearInterval(userTimer);
clearInterval(deviceTimer);
userTimer = null;
cityTimer = null;
deviceTimer = null;
});
},
下面进行测试
首先是做两个翻牌器,所以对其布局
<div class="equipment-top-title">
<ul>
<li v-for="item in doors" :key="item.id" :class="[{'d-online': item.id === 'd-online'}, {'d-off': item.id === 'd-off'}]">
<div class="number-scroll">
<span
:class="[{'flop-figure': !isNaN(ls)}, {'flop-comma': isNaN(ls)}]"
v-for="(ls, index) in item.valueArr"
:key="item.id + index"
>
<i v-if="!isNaN(ls)">0123456789</i>
<span v-else>{{ ls }}</span>
</span>
</div>
<div>{{item.name}}</div>
</li>
</ul>
</div>
css部分如下:这里用的less
.equipment-top-title {
width: 100%;
height: 40px;
overflow: hidden;
/* 样式这里就是把ul长度缩小到一个行字符的高度,多出的部分用overflow隐藏就行了 */
ul {
width: 368px;
background-color: #1674d6;
margin: 0;
display: flex;
justify-content:space-around;
text-align: center;
li {
background-color: #5ad8a6;
list-style: none;
color: rgba(255, 255, 255,0.7);
font-size: 14px;
.number-scroll{
position: relative;
color :#4a90e2;
font-size: 36px;
height :40px;
display: inline-flex;
align-items: center;
justify-content: center;
}
>p:first-child{
color: red;
font-size: 33px;
}
}
.d-off .number-scroll span{
color: red;
}
> li:first-child > p:first-child{
color: #4a90e2
}
.d-online{
margin: 0;
padding: 0;
}
.d-off{
margin: 0;
padding: 0;
}
}
}
然后把值派发给父组件
this.$parent.timedRefresh(this.doors, 'device')
在父组件中通过if判断类型进行翻牌效果
这时就可以获得两个遍历后的数字
总结:其主要思想就是将获取到的一个数据分割开来切割成一个一个数字,用0~9绑定对应的数字,从上往下依次滚动即可达到翻牌器的效果
设置文字滚动方式可以参考之前的文章Echarts前言——数字翻牌器在父组件中如何使用,这里就不一一演示了
最后看下效果