Vue 正计时器组件

工作中需实现时间正计时功能,同时涉及Vue父组件调用子组件的data和method。博客记录了实现过程,包含HTML和JS部分代码,通过props传递父组件方法到子组件,还提及在子组件中调用父组件方法及参数,子组件统计时分秒总和。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

工作中遇到了一个时间正计时的功能。
另外涉及到有Vue父组件调用子组件中的data和method,作为记录。
下面贴代码~

HTML部分

<template>
    <div class="timer">
        <div ref="startTimer">00:00:00</div>
    </div>
</template>

JS部分


<script>
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)
        }
    }
}
</script>

这里通过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

### 创建 Vue 前端计时器组件 #### 组件结构与文件布局 在一个名为 `vue-timer-app` 的项目中,最终的目录结构如下: ```plaintext vue-timer-app/ ├── src/ │ ├── components/ │ │ └── Timer.vue │ ├── App.vue │ └── main.js └── ... ``` 此结构有助于组织代码并保持清晰度[^1]。 #### 计时器组件开发 ##### Timer.vue 文件内容 以下是 `Timer.vue` 中的一个简单计时器实现方式。该组件能够启动和停止定时器,并实时更新视图中的时间信息。 ```html <template> <div class="timer"> <p>{{ formattedTime }}</p> <button @click="toggle">{{ isRunning ? 'Stop' : 'Start' }}</button> </div> </template> <script> export default { name: 'Timer', data() { return { startTime: null, intervalId: null, elapsedMilliseconds: 0, isRunning: false }; }, computed: { formattedTime() { let totalSeconds = Math.floor(this.elapsedMilliseconds / 1000); let seconds = ('0' + (totalSeconds % 60)).slice(-2); let minutes = ('0' + Math.floor(totalSeconds / 60)).slice(-2); return `${minutes}:${seconds}`; } }, methods: { start() { this.startTime = Date.now(); this.intervalId = setInterval(() => { this.elapsedMilliseconds += new Date().getTime() - this.startTime; this.startTime = new Date().getTime(); }, 100); // 更新频率设为每100毫秒一次 this.isRunning = true; }, stop() { clearInterval(this.intervalId); this.isRunning = false; }, toggle() { if (!this.isRunning) { this.start(); } else { this.stop(); } } }, }; </script> <style scoped> .timer p { font-size: 2em; } </style> ``` 上述代码定义了一个基本的计时器逻辑,在按钮点击事件触发下可以控制计时器的启停状态,并通过计算属性来格式化显示经过的时间[^5]。 #### 主应用入口配置 对于项目的主应用程序文件 `main.js` 来说,则需确保确初始化 Vue 应用程序实例以及挂载根节点到 HTML 页面上。 ```javascript import Vue from 'vue'; import App from './App.vue'; Vue.config.productionTip = false; new Vue({ el: '#app', render: h => h(App), }); ``` 这段脚本完成了整个 VueJS 应用的基础设置工作[^4]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值