vue template 代码:
<el-row >
<el-col :span="8" >
<p>今日数量:</p>
<span
ref="todayRef"
></span>
</el-col>
<el-col :span="8">
<p>历史数量:</p>
<span
ref="historyRef"
></span>
</el-col>
</el-row>
vue ts 代码:
// 接口地址
import {
getInfo,
} from "../../api";
setup() {
// 声明响应性变量
const state = reactive({
today: 0,
history: 0,
})
const todayRef: Ref<any> = ref(null);
const historyRef: Ref<any> = ref(null);
onMounted(() => {
let timer: any = null;
let i = 0;
todayRef.value.innerHTML = 0;
historyRef.value.innerHTML = 0;
getInfo().then((res: any) => {
{
// 解构数据
const { today, history} = res;
timer = setInterval(() => {
i += 1;
if (state.today < today) {
state.today+= 1;
// ref更改渲染数据
todayRef.value.innerHTML = state.today;
}
if (state.history < history) {
state.history+= 1;
// ref更改渲染数据
historyRef.value.innerHTML = state.history;
}
if (i > today && i > history) {
clearInterval(timer);
timer = null;
}
}, 50);
}
});
});
// 只有return出去的变量或方法才能在外部使用
return {
todayRef,
historyRef
}
}
实现数字滚动增加:
实现方案感觉难一点,需要配合css实现
template代码:
<el-col :span="8" >
<p>今日数据:</p>
<div
class="autoa"
ref="todayRef"
>
<template v-for="(item,index) in todayArr" :key="index">
<span :style="`left:${index*20}px`">
<em>0</em>
<em>1</em>
<em>2</em>
<em>3</em>
<em>4</em>
<em>5</em>
<em>6</em>
<em>7</em>
<em>8</em>
<em>9</em>
</span>
</template>
</div>
</el-col>
css代码
外层容器用relative,把0-9个数字竖排排在span标签内, span用来滚动数字
.autoa{
position:relative;
overflow: hidden;
height:40px;
span{
display: block; position:absolute; top:0px; opacity: 0;
transition: all 1s ease-in-out;
em{
display:block; font-style: normal; font-size: 32px;
}
}
}
js代码
// 声明响应性变量
const state = reactive({
todayArr:"0000",
})
const todayRef: Ref<any> = ref(null);
onMounted(() => {
getInfo().then((res: any) => {
{
// 解构数据
const { today, history} = res;
state.todayArr= today.toString();
for(let i = 0;i<state.todayArr.length; i++){
const item = Number(state.todayArr[i]);
todayRef.value.getElementsByTagName('span')[i].style.top = `-${item*40}px`;
todayRef.value.getElementsByTagName('span')[i].style.opacity = `1`;
}
}
});
});
// 只有return出去的变量或方法才能在外部使用
return {
todayRef,
}