Coder Social home page Coder Social logo

fengyuanchen / vue-countdown Goto Github PK

View Code? Open in Web Editor NEW
672.0 7.0 90.0 1.4 MB

Countdown component for Vue.js.

Home Page: https://fengyuanchen.github.io/vue-countdown/

License: MIT License

JavaScript 17.95% TypeScript 81.59% Shell 0.46%
countdown vue vue-component

vue-countdown's Introduction

vue-countdown

Coverage Status Downloads Version Gzip Size

Countdown component for Vue 3. For Vue 2, check out the v1 branch.

Main npm package files

dist/
├── vue-countdown.js         (UMD, default)
├── vue-countdown.min.js     (UMD, compressed)
├── vue-countdown.esm.js     (ECMAScript Module)
├── vue-countdown.esm.min.js (ECMAScript Module, compressed)
└── vue-countdown.d.ts       (TypeScript Declaration File)

Getting started

Installation

Using npm:

npm install vue@3 @chenfengyuan/vue-countdown@2

Using pnpm:

pnpm add vue@3 @chenfengyuan/vue-countdown@2

Using Yarn:

yarn add vue@3 @chenfengyuan/vue-countdown@2

Using CDN:

<script src="https://unpkg.com/vue@3"></script><!-- Vue.js is required -->
<script src="https://unpkg.com/@chenfengyuan/vue-countdown@2"></script>

Usage

import { createApp } from 'vue';
import VueCountdown from '@chenfengyuan/vue-countdown';

const app = createApp({});

app.component(VueCountdown.name, VueCountdown);
<vue-countdown :time="2 * 24 * 60 * 60 * 1000" v-slot="{ days, hours, minutes, seconds }">
  Time Remaining:{{ days }} days, {{ hours }} hours, {{ minutes }} minutes, {{ seconds }} seconds.
</vue-countdown>
<!-- <span>Time Remaining:1 days, 23 hours, 59 minutes, 59 seconds.</span> -->

Browser support

Same as Vue 3.

Versioning

Maintained under the Semantic Versioning guidelines.

License

MIT © Chen Fengyuan

vue-countdown's People

Contributors

dependabot[bot] avatar fengyuanchen avatar sqrtqiezi avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

vue-countdown's Issues

Didn't countdown, When didn't stay on page.

Countdown would stop working, When didn't stay on page and set interval was not 1000.

<countdown v-if="counting" :time="count" :interval="100"  tag="p" @countdownend="bidEnd" ref="countdownBid">
    <template scope="props">
        <h1 class="counting">{{ props.seconds }}</h1>
    </template>
</countdown>

Get countdownend event element

How to get countdownend event element?

Example: after countdownend I want to get parent element through event's target element and remove it from DOM. I tried to pass $event with countdownend call but I just get undefined back.

countdownend(event) {
    console.log('--- COUNTDOWN ENDED ---')
    console.log(this)
}

console.log(this) outputs Vue object
console.log(event) outputs undefined

How to change the text to something else, if the countdown elapsed?

How to change the text to something else instead of displaying 00:00, if the countdown elapsed?

<countdown :time="timeLeft" :transform="transform">
    <template slot-scope="props">{{ props.minutes }}:{{ props.seconds }}</template>
</countdown>
        var app = new Vue({
          el: '#app',
          data: function () {
                var now = new Date();
                return {
                    timeLeft: new Date('2020-10-15T00:05:32.000Z') - now,
                }
            },
             methods: {
                transform(props) {
                  Object.entries(props).forEach(([key, value]) => {
                    props[key] = value < 10 ? `0${value}` : value;
                  });
                  return props;
                },
              },
        })

Enhancement: add leading zero

Add leading zero to days, hours, minutes and seconds.

Something like this:

twodigits (value) {
  if (value.toString().length <= 1)
      return '0' + value.toString()
    return value.toString()
}

:auto-start="false" bug

For example: I have a countdown time set for 2 minutes. I start the countdown after 30 seconds and then switch to another tab and go back to countdown immediately, and instead of seeing about 2 minutes left I see 1 minute 30 seconds.

I added endTime and totalMilliseconds at the beginning of the start function. It seems like fixes the problem

start: function start() {
    this.totalMilliseconds = this.time;
    this.endTime = this.now() + this.time;
...
}

End event not fired after visibility change

If the countdown ends while the user is in a different tab and then returns to the tab, the end event is not fired. The countdown is at 0:00, but no event is triggered.

Tested in Chrome (78) and Firefox (70).

Possible solutions:

  • Use document.hidden instead of document.visibilityState (hidden is either true or false while visibilityState has other options besides hidden and visible) — that's how visibility.js does it.
  • Add a flag if the end event was run and on returning to tab, dispatch it if it wasn't dispatched before

how to add end date ?

hi .

i want add a date time to counting down .
can use this ?

for example :
<countdown :timestamp="1561059000"> <template slot-scope="props">Time Remaining:{{ props.days }} days, {{ props.hours }} hours, {{ props.minutes }} minutes, {{ props.seconds }} seconds.</template> </countdown>

Question: multiple countdown components in the same page

How can I control multiple countdown components in the same page i.e.:

this.$refs.countdown0.stop()
this.$refs.countdown1.start()

I have a table and for each row I have a countdown and I need to be able to control each countdown component separately.

Thanks!

【已解决】关于计时器一开始就触发countdownend 事件的例子

  <div id="app">
      <countdown :time="time" :interval="100" tag="p" :countdownend="alert('end')">
        <template slot-scope="props">New Year Countdown:{{ props.days }} days, {{ props.hours }} hours, {{ props.minutes }} minutes, {{ props.seconds }} seconds.</template>
      </countdown>
      <countdown :time="time" tag="p"  :countdownend="alert('end')">
        <template slot-scope="props">Christmas Time Remaining: {{ props.totalDays }} days / {{ props.totalHours }} hours / {{ props.totalMinutes }} minutes / {{ props.totalSeconds }} seconds.</template>
      </countdown>
      <button type="button" class="btn btn-primary" :disabled="counting" @click="countdown">
        <countdown v-if="counting" :time="60000" :leading-zero="false" @countdownend="countdownend">
          <template slot-scope="props">Fetch again {{ props.totalSeconds }} seconds later</template>
        </countdown>
        <span v-else>Fetch Verification Code</span>
      </button>
    </div>
    <p class="count"></p>

关于计时器一开始就触发countdownend 事件的例子

Add pause and continue to readme?

Just noticed there's no reference of the 'pause' or 'continue' methods in the readme, even though they are available. Is there a reason they are left off the readme? Love the countdown component, thanks for your work.

data.totalMilliseconds is undefined

I noticed that the component doesn't have the ability to get data.totalMilliseconds (although it was listed in documentation). Screenshot of data object below

Screenshot 2019-04-09 at 21 56 46

Prevent Countdown stop when navigating away

Hi,

I want the counter to keep counting down when an user navigates away from the page. Now it resets to 0:00. My code sample is the basic one from the readme.

How can i prevent that the counter stops when navigating away?

Wrong behavior in handleVisibilityChange method

Hi!
I noticed, if you open the demo in a new tab and then switch to it, we get a duplicate update call, and it turns out that the progress event emits twice per interval.
Remark: it's not every time behavior, but it's shows up from time to time.

Using requestAnimationFrame loses time

When comparing a 7 minute countdown timer with a physical stopwatch, this library loses around a second a minute resulting in a loss of ~7 seconds.

The same applies when using the setTimeout() fallback although over 7 minutes the countdown timer only loses ~2 seconds.

Is there anyway to compensate for this drift? I am using the countdown timer for examinations (in an iOS app) which must allow a student exactly 7 minutes to a complete a task.


It looks like this line here contributes to the loss of time because timestamp - start may be (marginally) greater than delay (1000 ms) and over time this builds up.

How to countdown on fixed date?

Right now from the example the timer starts when the page loads. I want the countdown to minus from a fixed date. for example the date is 29th feb ... so how can i mention date as 28 feb - now. to get the proper countdown going. thanks.

What the bug??

You should watch this Video

I used this.$refs.countdownBid.count = 10000; when hit a button.

Seem like error when back to the page, It will get first count time.

file package.json used in laravel project.

{
    ...
    "devDependencies": {
        "@xkeshi/vue-countdown": "^0.4.0",
        "axios": "^0.16.2",
        "bootstrap-sass": "^3.3.7",
        "cross-env": "^5.0.5",
        "jquery": "^3.2.1",
        "laravel-mix": "^1.4.5",
        "lodash": "^4.17.4",
        "moment": "^2.18.1",
        "vue": "^2.4.4"
    },
    ...
}

With v0.3.0 there was no this bug or error.

countdownend fired when reaching -1

I'm experiencing an issue where the countdownend is first fired when the countdown reaches -1

I don't know if this is to be expected, but to me it seems like a bug.

时间不准确?

<vue-countdown :time="toMillisecond(1538537400000)" :leading-zero="false">
  <template slot-scope="props">{{ props.days }}天 {{ props.hours }}小时 {{ props.minutes }}分钟 {{ props.seconds }}秒</template>
</vue-countdown>
toMillisecond(input) {
      console.log(new Date(input));
      return new Date(input) - new Date();
}

显示的倒计时却为0天 17小时 12分钟 43秒,而正确值应是1天 5小时 12分钟 12秒

已经快给逼疯了... 请问哪儿有问题呢...?

auto-start="false" bug

with auto-start set to false while clicking off the window and then back onto window the timer jumps the amount of time that wouldve passed as if it was running. my code is split up between $store and the uploader.vue basically responding to successful upload to firebase, I've got a commit setting timer to true which in turn starts the count down. however this bug has hurt my brain cause I kept thinking it was something in my code causing it, but I've flipped and changed around so many times that the only thing left is the component. I've even tried changing the component variable auto-start default to false, but to no avail. some gifs to show what I mean:
auto-start = "false"
auto-start-onfalse
auto-start = "false" and explicit setting of vm.counting = false and still occuring
auto-start-onfalse countingsettofalse

my code references:
================= countdown component tag (upload.vue)
<countdown :auto-start="false" ref="countdown" :time="5 * 60 * 1000" :interval="100"> <template slot-scope="props">Time Remaining:{{ props.minutes }} minutes, {{ props.seconds }} seconds.</template> </countdown>
======================== (upload.vue)
watch: { initTimer () { if (this.$store.getters.timer) { this.$refs.countdown.start() } else { this.$refs.countdown.stop() } } }

============== The only thing I'm not sure about is if it make a difference where I'm importing the @xkeshi/vue-countdown. At the moment I've got it importing onto the upload.vue which is where I'm calling the above watch

======== the following is in my index.js for store
pushToFirebase ({commit}, payload) { ...... }, function (error) { ...... }, function complete () { ...... commit('setTimer', true) })

and that commit in the complete function is where I set the initTimer on my .vue page to true which starts the timer...

mayb it is something in my code... I'm a nub at this. So any pointers will be appreciated. My apologies if it is my noob code

How to 'restart' the countdown?

Hi there! Thanks so much for this. Nice and easy.

How would I go about restarting the timer. Eg, bring the time back to the originally input date?

Cheers!

能不能加一个活动倒计时,包括预热的例子

用在活动预售页面上,如:
“距离开售还有xx天xx时xx分”,到了开售时间变成“距离结束还有xx天xx时xx分”,结束以后再变成“活动结束”。
有3个事件——未开始,进行中,已结束

End event on different tab

If I have a countdown running and tab to a different browser tab, the end event doesn't fire before I tab back.

Is there a way to make it fire even if I'm not on the tab, when the countdown ends?

pause() function not enabled

pause() doesn't work if installed with npm as the dist files were not changed to include it, but you can add it manually.

How to reset the countdown so that it starts from the beginning again?

I would like to reset the counter (see resetCountdown) and tried it with the following but once I stopped and started it again, it doesn't work a second time. The counter just continues counting down on and on.

I found #39 but as you see in my code, I do just set the time prop again but as I said, it just works once.

<template>
    <div>
        <button type="button" @click="resetCountdown">Reset counter</button>

        <countdown ref="countdown" :time="time" :transform="transform" :emit-events="false">
            <template slot-scope="props">{{ props.minutes }}:{{ props.seconds }}</template>
        </countdown>
    </div>
</template>

<script>
    import VueCountdown from "@chenfengyuan/vue-countdown";

    export default {
        components: {
            'countdown': VueCountdown
        },
        data() {
            return {
                time: 5 * 60 * 1000,
            };
        },
        methods: {
            resetCountdown() {
                this.time = 5 * 60 * 1000;
            },
            transform(props) {
                Object.entries(props).forEach(([key, value]) => {
                    props[key] = value < 10 ? `0${value}` : value;
                });

                return props;
            },
        }
    }
</script>

event ref

set the even "end" using $ref.countdown

npm包下载的和source下载的与源码不一致

https://github.com/xkeshi/vue-countdown/archive/v0.5.0.zip

和npm 安装的 与 https://github.com/xkeshi/vue-countdown/blob/master/src/index.js 不一致

下载的

    init() {
      const { time } = this;

      if (time > 0) {
        this.count = time;
        this.endTime = this.now() + time;
      }
    },

源码

init() {
      const { time } = this;

      if (time > 0) {
        this.count = time;
        this.endTime = this.now() + time;

        if (this.autoStart) {
          this.$nextTick(() => {
            this.start();
          });
        }
      }
    }

Detect which component called method "@progress"?

I have several components in my table with different times to count to. The problem is i need to send request to server every second, so the time as I refresh will change to correct time. (deadlines functionality)

Here is my code:

<div class="table-row" :key="task.id" v-for="(task, id) in tasks">
   <div class="task-deadlines">
      <countdown :time="task.seconds" @progress="handleCountdownProgress" :auto-start='true'>
      <template slot-scope="props">{{ props.days }} д. {{ props.hours }} ч. {{ props.minutes }} м. {{ props.seconds }} с.</template>
      </countdown>
   </div>
</div>

Method:

handleCountdownProgress(data){
   let time = data.totalMilliseconds;
   // cant get an id here...
   this.$store.dispatch('UPDATE_TIME', { id: id, seconds: time });
}

Is there any way to do this?

Change tab or windows

When the countdown is started and you change the windows or active tab it may cause a strange behaviour, stop, slow or fast changes in the countdown component, any idea to bypass this issue?
Thanks in advance

Leading zeros

Are there plans for this component to add leading zeros in the timer?

For example: instead of 1 days, 5 hours, it would be 01 days, 05 hours.

If not, I'd like to go ahead and do a PR.

this.$refs.countdown.start is not a function

Why do I get this error when I try to do the start() method:
Uncaught TypeError: this.$refs.countdown.start is not a function
When I console.log(this.$refs.countdown) I get the VueComponent of the Countdown successfully.

<countdown :auto-start="false" :time="7000" @countdownend="countdownend()" ref="countdown"> <template slot-scope="props" v-if="props.totalSeconds!=0">{{ props.totalSeconds }}</template> </countdown>

Vue method:
startcountdown(){ console.log(this.$refs.countdown); this.$refs.countdown.start(); },

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.