工作中遇到了一个时间正计时的功能。
另外涉及到有Vue父组件调用子组件中的data和method,作为记录。
下面贴代码~
HTML部分
- <template>
- <div class="timer">
- <div ref="startTimer">00:00:00div>
- div>
- template>
JS部分
-
- export default {
- name:'Timer',
- props:{
- time:{
- type:Number
- }
- },
- data() {
- return {
- timer: "",
- hour: 0,
- minutes: 0,
- seconds: 0,
- cr: ''
- }
- },
- created() {
- this.timer = setInterval(this.startTimer, 1000);
- },
- methods: {
- startTimer() {
- this.seconds += 1;
- if (this.seconds >= 60) {
- this.seconds = 0;
- this.minutes = this.minutes + 1;
- }
-
- if (this.minutes >= 60) {
- this.minutes = 0;
- this.hour = this.hour + 1;
- }
- this.$refs.startTimer.innerHTML = (this.hour < 10 ? '0' + this.hour: this.hour) + ':' + (this.minutes < 10 ? '0' + this.minutes: this.minutes) + ':' + (this.seconds < 10 ? '0' + this.seconds: this.seconds);
- this.cr = this.seconds
- },
- stop () {
- clearInterval(this.timer)
- },
- start () {
- this.timer = setInterval(this.startTimer, 1000)
- }
- }
- }
这里通过props把父组件的方法传递给子组件
这里我们在子组件中定义
<Time :time="time" ref="headerChild">Time>
我要调用父组件中的start()的方法以及参数,方法如下
- this.$refs.headerChild.stop()
- this.$refs.headerChild.seconds
注:子组件中统计时分秒总合
- var timeHour = this.$refs.headerChild.hour
- var timeMinutes = this.$refs.headerChild.minutes
- var timeSeconds = this.$refs.headerChild.seconds
- var totalTime = timeHour * 3600 + timeMinutes * 60 + timeSeconds