Skip to content
Open
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions docs/keep-in-session.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
```vue
<template>
<div>
<count-down :seconds="59" :hours="1" keep-in-session="my_keep" ref="cd" />
<button @click="onClick('start')">start</button>
<button @click="onClick('pause')">pause</button>
<button @click="onClick('reset')">reset</button>
</div>
</template>
<script>
export default {
methods: {
onClick(m) {
this.$refs.cd[m]()
}
},
}
</script>
```
37 changes: 37 additions & 0 deletions src/count-down.vue
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,13 @@ export default {
format: {
type: String,
default: ''
},

/**
* keep countdowm time in session
*/
keepInSession: {
type: String
}
},
data() {
Expand Down Expand Up @@ -96,6 +103,20 @@ export default {
},
mounted() {
if (this.autoplay) this.start()
window.addEventListener('unload', this.setSession)
let session = sessionStorage.getItem(this.keepInSession)
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

先判断this.keepInSession为true再去getItem吧

if (session) {
session = JSON.parse(session)
const mountTime = session.rafId
? Number(new Date()) - session.unloadTime
: 0
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

记rafId有啥用

this.elapsed = this.time - (session.countdown - mountTime)
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

直接记startTime不就行了?不用又记unloadTime又记countdown吧

}
},
beforeDestroy() {
cancelAnimationFrame(this.rafId)
this.setSession()
window.removeEventListener('unload', this.setSession)
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

直接在beforeDestroy里setSession就行了吧,为啥要listen unload呢?

},
methods: {
/**
Expand All @@ -115,6 +136,7 @@ export default {
/**
* 计时结束事件
*/
this.clearSession()
this.$emit('finish')
}
})
Expand All @@ -136,6 +158,21 @@ export default {
reset() {
this.pause()
this.elapsed = 0
},
setSession() {
if (this.keepInSession) {
sessionStorage.setItem(
this.keepInSession,
JSON.stringify({
countdown: this.countdown,
unloadTime: Number(new Date()),
rafId: this.rafId
})
)
}
},
clearSession() {
sessionStorage.removeItem(this.keepInSession)
}
}
}
Expand Down