效果
组件代码
<template>
<span v-bind="$attrs">
{{ screenNum }}
</span>
</template>
<script>
export default {
props: {
value: Number,
animation_time: {
type: Number,
default: 2,
},
},
name: 'ChangeNum',
data() {
return {
screenNum: this.value,
}
},
methods:{
async sleep(millisecond) {
return new Promise(function (reslove){
setTimeout(reslove, millisecond)
})
}
},
watch: {
async value(newVal, oldVal) {
const totalTime = this.animation_time * 1000
const times = 20 //数字变化次数
const intervalTime = totalTime/times
// 每次变化差值
const distance = Math.floor(( newVal - oldVal ) / times)
for (let index = 0; index < times; index++) {
this.screenNum += distance
await this.sleep(intervalTime)
}
this.screenNum = newVal
},
},
}
</script>
父组件代码
<template>
<div id="app">
<!--<HelloWorld msg="Welcome to Your Vue.js App"/>-->
<ChangeNum :value="number" :animation_time="2" style="color: white" class="num-span"></ChangeNum>
<button @click="setNum">change</button>
</div>
</template>
<script>
//import HelloWorld from './components/HelloWorld.vue'
import ChangeNum from './components/ChangeNum.vue'
export default {
name: 'App',
components: {
//HelloWorld,
ChangeNum,
},
data() {
return {
number: 0
}
},
methods: {
setNum(){
this.number= Math.floor(Math.random() * 10000)
}
}
}
</script>
<style>
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
}
.num-span{
background: forestgreen;
font-size: 30px;
margin-right: 10px;
}
</style>
父组件中可以定义span的样式, 暂未考虑小数