Vue Js Track Time Spent on Page: Vue.js is a JavaScript framework that allows developers to build dynamic user interfaces for web applications. To track the time spent on a Vue.js page, you can use the created
lifecycle hook to initialize a variable with the current timestamp when the component is created. Then, use the beforeDestroy
lifecycle hook to calculate the difference between the current timestamp and the initial timestamp, which gives you the time spent on the page. You can then send this data to an analytics tool or server to track user behavior and improve the user experience. Overall, using Vue.js lifecycle hooks makes it easy to track time spent on a page and gather valuable insights.
How can Vue.js be used to measure the amount of time a user spends on a page?
This script uses the Vue.js framework to track and display the time that a user spends on a webpage.
In the data
object, it initializes four variables: time
(the amount of time spent on the page in milliseconds), intervalId
(the ID of the setInterval() function that updates the time every second), pageLoadTime
(the timestamp of when the page was loaded), and isActive
(a boolean value that tracks whether the page is currently visible to the user).
The created
hook sets up the setInterval() function to update the time
variable every second. This function only runs when isActive
is true
.
The computed
property formats the time
variable into minutes and seconds, and the mounted
hook listens for the visibilitychange
event, which fires when the user switches to another tab or minimizes the browser window. When the page becomes hidden, isActive
is set to false
, pausing the timer. When the page becomes visible again, isActive
is set to true
, and the pageLoadTime
variable is updated to reflect the time that the page was hidden.
Finally, the destroyed
hook clears the setInterval() function when the component is destroyed, ensuring that the timer stops running when the user navigates away from the page.
Vue Js Measure Time Spent on Page Example
<div id="app">
<p>Time Spent on Page: {{ formattedTime }}</p>
</div>
<script type="module">
const app = new Vue({
el: "#app",
data() {
return {
time: 0,
intervalId: null,
pageLoadTime: Date.now(),
isActive: true,
};
},
created() {
this.intervalId = setInterval(() => {
if (this.isActive) {
this.time = Date.now() - this.pageLoadTime;
}
}, 1000);
},
destroyed() {
clearInterval(this.intervalId);
},
computed: {
formattedTime() {
const minutes = Math.floor(this.time / 60000);
const seconds = ((this.time % 60000) / 1000).toFixed(0);
return `${minutes}:${(seconds < 10 ? "0" : "")}${seconds}`;
},
},
mounted() {
document.addEventListener("visibilitychange", () => {
this.isActive = !document.hidden;
if (this.isActive) {
this.pageLoadTime = Date.now() - this.time;
}
});
},
});
</script>