如何在Vue.js中创建简单的10秒倒计时

时间:2019-04-20 12:40:37

标签: javascript vue.js

我想从10倒数到0

我使用普通的javascript在线找到了解决方案,但可以说我想在Vue中实现。 jQuery中的解决方案

Create a simple 10 second countdown

<template>
   {{ countDown }}

</template>

<script>
  export default {
    computed: {
       countDown() {
         // How do i do the simple countdown here?
       }

    }

  }

</script>

如何在Vue.js中重新创建相同的功能?

谢谢

7 个答案:

答案 0 :(得分:22)

虽然可接受的答案有效且很好,但实际上可以通过使用Vue.js watchers以稍微简单的方式实现:

<template>
    {{ timerCount }}
</template>

<script>

    export default {

        data() {
            return {
                timerCount: 30
            }
        },

        watch: {

            timerCount: {
                handler(value) {

                    if (value > 0) {
                        setTimeout(() => {
                            this.timerCount--;
                        }, 1000);
                    }

                },
                immediate: true // This ensures the watcher is triggered upon creation
            }

        }
    }

</script>

使用此方法的好处在于,只需设置timerCount的值即可立即重置计时器。

答案 1 :(得分:2)

请检查是否适合您。

apiVersion: apps/v1
kind: Deployment
metadata:
  name: app-typescript
  labels:
    app: app-typescript
spec:
  selector:
      matchLabels:
        app: app-typescript
  replicas: 1
  minReadySeconds: 15
  strategy:
    type: RollingUpdate    
    rollingUpdate:
      maxUnavailable: 1                                   
      maxSurge: 1 
  template:
    metadata:
      labels:
        app: app-typescript
    spec:
      containers:
      - name: api
        image: dockerhuborg/api:latest
        imagePullPolicy: Always
        env:
          - name: "ENV_TYPE"
            value: "production"
          - name: "NODE_ENV"
            value: "production"
          - name: "MONGODB_URI"
            value: "mongodb://mongo-mongodb/db"
        ports:
        - containerPort: 4000
      imagePullSecrets:
      - name: regcred

答案 2 :(得分:1)

如果有人使用Luxon的DateTime对象而不是本机JS的Date对象。

<template>
  <span v-if="timer">
    {{ timeCalculated }}
  </span>
</template>

<script>
import { DateTime } from 'luxon'

export default {
  name: 'CountDownTimer',

  props: {
    endDate: {
      type: String,
      required: true
    }
  },

  data () {
    return {
      now: DateTime.local(),
      timer: null
    }
  },

  computed: {
    timeCalculated () {
      const endDateDateTimeObj = DateTime.fromISO(this.endDate)
      const theDiff = endDateDateTimeObj.diff(this.now, ['hours', 'minutes', 'seconds'])

      return `${theDiff.hours}:${theDiff.minutes}:${Math.round(theDiff.seconds)}`
    }
  },

  watch: {
    endDate: {
      immediate: true,

      handler (endDateTimeStr) {
        const endDateTimeObj = DateTime.fromISO(endDateTimeStr)

        if (this.timer) {
          clearInterval(this.timer)
        }

        this.timer = setInterval(() => {
          this.now = DateTime.local()

          if (this.now > endDateTimeObj) {
            this.now = endDateTimeObj
            clearInterval(this.timer)
          }
        }, 1000)
      }
    }
  },

  beforeDestroy () {
    clearInterval(this.timer)
  }
}
</script>

在我的情况下,endDate具有字符串类型,因为该值是从JSON恢复的。您可以轻松地将其更改为原始的DateTime对象。

答案 3 :(得分:0)

因此本质上在vue.js中执行此操作与在JS中执行相同。
您可以走很多路,但是我要做的方式如下

<template>
    {{ countDown }}
</template>

<script>
    export default {
    created() {
        window.setInterval(autoIncrementTimer, 1000)
    },
    methods() {
        autoIncrementTimer() {
            if (this.timerCount =< 0) {
                return
            }
            timerCount -= 1;
        }
    }
    data() {
        return {
               timerCount: 0;
        }
    },
}

</script>

为了将其作为计算属性来实现,您需要编写一个get和set函数,而总体计算道具似乎对于此任务来说是一个过大的杀伤力。

总结一下:

  1. 在数据中创建一个变量,以存储当前值。

  2. 在组件Create()上,使用window.setInterval创建重复功能和间隔时间。

  3. 在您的函数中根据需要应用安全性和递减。

如您所见,上面的<script>实际上是普通js。

答案 4 :(得分:0)

这是我为倒数计时器制作的组件:

<template>
  <div>
    <slot :hour="hour" :min="min" :sec="sec"></slot>
  </div>
</template>

<script>
export default {
  props : {
    endDate : {  // pass date object till when you want to run the timer
      type : Date,
      default(){
        return new Date()
      }
    },
    negative : {  // optional, should countdown after 0 to negative
      type : Boolean,
      default : false
    }
  },
  data(){
    return{
      now : new Date(),
      timer : null
    }
  },
  computed:{
    hour(){
      let h = Math.trunc((this.endDate - this.now) / 1000 / 3600);
      return h>9?h:'0'+h;
    },
    min(){
      let m = Math.trunc((this.endDate - this.now) / 1000 / 60) % 60;
      return m>9?m:'0'+m;
    },
    sec(){
      let s = Math.trunc((this.endDate - this.now)/1000) % 60
      return s>9?s:'0'+s;
    }
  },
  watch : {
    endDate : {
      immediate : true,
      handler(newVal){
        if(this.timer){
          clearInterval(this.timer)
        }
        this.timer = setInterval(()=>{
          this.now = new Date()
          if(this.negative)
            return
          if(this.now > newVal){
            this.now = newVal
            this.$emit('endTime')
            clearInterval(this.timer)
          }
        }, 1000)
      }
    }
  },
  beforeDestroy(){
    clearInterval(this.timer)
  }
}
</script>

答案 5 :(得分:0)

将其制成组件,以便您可以重复使用。

<body>
    <div id="app">
        <counter></counter>
        <counter></counter>
        <counter></counter>
    </div>
    <script>
        Vue.component('counter', {
            template: '<button v-on:click="countDownTimer()">{{ countDown }}</button>',
            data: function () {
                return {
                    countDown: 10,
                    countDownTimer() {
                        if (this.countDown > 0) {
                            setTimeout(() => {
                                this.countDown -= 1
                                this.countDownTimer();
                            }, 1000)
                        }
                    }
                }
            }
        })

        const app = new Vue({
            el: '#app'
        })
    </script>
</body>

答案 6 :(得分:0)

使用日期。

<template>
  <div>{{ time }}</div>
</template>

<script>
export default {
  name: 'Timer',

  props: ['seconds'],

  data: () => ({
    interval: undefined,
    end: new Date(0, 0, 0),
    current: new Date(0, 0, 0, 0, 0, this.seconds)
  }),

  computed: {
    time: {
      get() {
        return this.current.getSeconds();
      },

      set(d) {
        this.current = new Date(0, 0, 0, 0, 0, this.current.getSeconds() + d);
      }
    }
  },

  methods: {
    countDown() {
      this.end >= this.current
        ? clearInterval(this.interval)
        : (this.time = -1);
    }
  },

  created() {
    this.interval = setInterval(this.countDown, 1000);
  }
};
</script>