1. 程式人生 > 其它 >Vue數字動態變化元件

Vue數字動態變化元件

效果

元件程式碼

<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的樣式, 暫未考慮小數