// 在 Vue 组件中获取当前时间的示例代码
<template>
<div>
<p>当前时间: {{ currentTime }}</p>
</div>
</template>
<script>
export default {
data() {
return {
currentTime: ''
};
},
created() {
this.updateTime();
// 每秒更新一次时间
setInterval(this.updateTime, 1000);
},
methods: {
updateTime() {
const now = new Date();
// 格式化时间为 "YYYY-MM-DD HH:mm:ss"
this.currentTime = now.toLocaleString();
}
}
};
</script>
<style scoped>
/* 样式可以根据需要自定义 */
</style>
模板部分 (<template>
):
{{ currentTime }}
来显示当前时间。脚本部分 (<script>
):
data()
返回一个对象,其中包含 currentTime
,用于存储当前时间。created()
生命周期钩子在组件创建时调用 updateTime
方法,并设置每秒调用一次 updateTime
的定时器。updateTime
方法使用 new Date()
获取当前时间,并通过 toLocaleString()
方法格式化为本地时间字符串,然后将其赋值给 currentTime
。样式部分 (<style scoped>
):
上一篇:vue markdown
下一篇:vue安装教程
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站