Vue.js 定时刷新页面:使用 setInterval 实现自动更新 - 代码示例
在 Vue.js 中,可以使用 `setInterval` 函数来设置定时刷新页面。在 Vue 的生命周期方法 `mounted` 中,使用 `setInterval` 函数来调用刷新页面的方法。\n\n以下是一个示例:\n\nhtml\n<template>\n <div>\n <h1>当前时间:{{ currentTime }}</h1>\n </div>\n</template>\n\n<script>\nexport default {\n data() {\n return {\n currentTime: null,\n };\n },\n mounted() {\n // 在mounted生命周期方法中设置定时刷新页面\n setInterval(() => {\n this.refreshPage();\n }, 1000); // 每秒刷新一次\n },\n methods: {\n refreshPage() {\n // 更新当前时间\n this.currentTime = new Date().toLocaleTimeString();\n },\n },\n};\n</script>\n\n\n在上面的示例中,`mounted` 生命周期方法中使用 `setInterval` 函数来每秒调用 `refreshPage` 方法,更新 `currentTime` 的值并刷新页面。然后在模板中使用 `{{ currentTime }}` 来显示当前时间。\n\n注意:定时刷新页面可能会导致页面性能问题,因此要根据实际需求谨慎使用。
原文地址: https://www.cveoy.top/t/topic/qttH 著作权归作者所有。请勿转载和采集!