Suspend features for moving between pages in history

In the application, we have two main pages - Home.vue and Statistics.vue. The Home.vue page renders the TableFields.vue component. On the Home page, there are fields with numbers that have an initial value of "3" set upon page load. An interval running a calculate function adds numbers every two seconds. How can we ensure that when transitioning from '/' to '/statistics', all ongoing calculations are paused, and then resumed when returning back? Below each field on the home page, there are buttons that toggle the setInterval() function to stop or resume the calculations. Essentially, when moving from "/" to "/statistics", we need to trigger clearInterval() to stop the calculations on the "/" page. @Saksham TableFields.vue:

<template>
  <div>
    <table class="table-a">
      <tr>
        <th>A</th>
        <td class="sign">{{ this.randomSign.A }}</td>
        <td>{{ initialValue.A }}</td>
        <td v-show="this.randomSign.A == '+'">&#x2B06;</td>
        <td v-show="this.randomSign.A == '-'">&#x2B07;</td>
      </tr>
    </table>
    <button @click="toggleIntervalA()">
      <span v-show="this.startStop.A">Stop</span>
      <span v-show="!this.startStop.A">Start</span>
    </button>
    <table class="table-b">
      <tr>
        <th>B</th>
        <td class="sign">{{ this.randomSign.B }}</td>
        <td>{{ initialValue.B }}</td>
        <td v-show="this.randomSign.B == '+'">&#x2B06;</td>
        <td v-show="this.randomSign.B == '-'">&#x2B07;</td>
      </tr>
    </table>
    <button @click="toggleIntervalB()">
      <span v-show="this.startStop.B">Stop</span>
      <span v-show="!this.startStop.B">Start</span>
    </button>
  </div>
</template>

<script>

export default {
  name: 'TableFields',
  props: {
    changesA: {
      type: Array,
      required: false
    },
    changesB: {
      type: Array,
      required: false
    }
  },
  data () {
    return {
      // Data properties removed for brevity
    }
  },
  methods: {
    // Methods logic removed for brevity
  },
  mounted () {
    // Mounted logic removed for brevity
  },
  beforeDestroy () {
    // Before destroy logic removed for brevity
  }
}
</script>

<style lang="scss" scoped>
// Styling rules removed for brevity
</style>

Project repository: link

Answer №1

Consider implementing the beforeDestroy() hook to transfer the counter to either the root component or the Vuex store (if applicable). Then, retrieve the counter in the mounted() hook when returning to the route to continue from where you left off.

Here's an example of how to use this in your component:

export default {
...
    beforeDestroy () {
        this.$root.counter = this.counter;
    },
    mounted () {
        this.counter = this.$root.counter || 0;
    }
...
}

I have set up a demo in a sandbox at https://codesandbox.io/s/preserve-timer-state-2osi7, which maintains the timer state even when navigating away and resumes it accordingly.

Additional Note:

Based on your comment, it appears that you are trying to assign a value to a property within an undefined object. Initially, there is no initialValue property in the root component, and you are attempting to access a nested property A.

You should first verify if initialValue exists before accessing A:

this.initialValue.A = this.$root.initialValue && this.$root.initialValue.A ?  this.$root.initialValue.A : 3

Also, ensure that your data includes initialValue as an empty object:

initialValue: {}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Oops! There seems to be a problem with the Node.js App. The MongooseError is indicating that the parameter `uri` in the `openUri()` function should be a string,

I've encountered an issue with my Next.js app involving MongoDB that I've been struggling to resolve. Hoping someone here can provide some insight and help me out. This is quite crucial for my project. First, I'll share the code from my serv ...

What could be causing the delay in response times from these unpredictable APIs within the Express server?

We are currently experiencing performance issues with our Express.js server and MongoDB database. Randomly, some API requests are taking too long to respond or timing out throughout the day. Our application is in production, hosted on two AWS instances wit ...

Can someone help me extract a specific portion and display the dimensions of the area?

In order for the mouse to create a selection range, simply release the mouse after making your selection. The selected area will display the values of width and height on both the X-axis and Y-axis in the designated fields. I am facing this issue and woul ...

Show a webpage depending on specific JavaScript criteria

I have a condition in my JavaScript code that determines whether or not a user should be granted access to a specific page. However, I don't want users to be able to directly access this page even if they know the URL. This page contains both HTML and ...

Ensuring Consistent Data in Web Forms When Editing a User's "Points" Field

In the process of creating a booking system, I am faced with an issue regarding how points are allocated to users. An admin can assign points to a user through a form, which the user then uses when booking a slot. The problem arises when the admin opens th ...

Initialization of Angular provider $get is missing

Within my 'app.js' file, I have the following code that is used in my config to set up $navigationProvider.doSomething(). When running this code, Test1 and Test3 are alerted correctly, but I'm having trouble with getting my this.$get method ...

Is it possible to load Angular.js without any references?

In the process of reverse engineering a User Interface that is operational but has a few bugs. Created using HTML, CSS, and JavaScript with data acquired through a REST API. The interface is designed for a Windows environment. While examining the index.ht ...

Ways to retrieve the page name where the script originates from

I have a function that is triggered from three different pages. Each page involves adding an attribute to a specific div. For instance: <div id="posts" page="home"></div> <div id="posts" page="feed"></div> <div id="posts" page= ...

Utilizing node.js for manipulating files (JSON) through reading and writing operations

There is an issue with my function that reads a JSON file and updates it using the fs.writeFile method. When I invoke this function multiple times, it fails to update the file properly. After the first call, it adds extra curly brackets at the end of the J ...

Unexpected behavior observed in JavaScript and AJAX functionality

In my web development project, I've decided to incorporate JavaScript and AJAX for the signup form functionality. However, I seem to be facing some challenges as I try to post all the textbox values from the signup form through AJAX. The code snippe ...

Text input setting for jQuery UI Slider

Currently, I am utilizing jQuery UI sliders to input values in text boxes. However, I would like this functionality to be bidirectional; meaning if a value is entered into the text box, I want the slider to move to the corresponding position. I am unsure ...

Is there a way to incorporate jQuery validation similar to MVC data annotation?

In my MVC project, I have a master/details view page. The Details section is actually a partial view containing input fields and a save button displayed below. <button type="button" id="btnAddDetails" class="btn btn-primary">Add Details <span cl ...

Guide to implementing two methods in a @click event with vue.js?

Here is the code I've been working on, and my goal is to incorporate CHANGEBUTTONS into the onclick event that resembles @click. <button @click="enviarform2" value="Delete from favorites" style="font-weight: 700;color:#428bca;margin-left:30px;heig ...

dual slider controls on a single webpage

I am attempting to place two different sliders on the same page. When I implement the following code for one slider, it functions correctly: <h3>Strength of Belief</h3> <div class="slidecontainer"> <div class="slider_left"> < ...

What is the best way to extract a JSON value and use it across multiple functions?

Currently, everything seems to be working fine. However, I'm unsure about the correct way to call the json data. I attempted using a direct link but it didn't work. Do I need to modify the "data" parameters? I'm confused because I saw that ...

How can we map a promise that resolves to foo to a new promise that resolves to bar?

I am working on a function that uses an XMLHttpRequest to retrieve data and returns a promise with the response. But now I want to modify it so that the promise only contains a specific string from the response. Instead of resolving to response = {status ...

Creating a custom directive in AngularJS that utilizes an event listener

I am currently working on designing a custom directive that includes a text box. When a user clicks a button, the text box should expand and become focused. If the user then clicks away from the expanded text box, it should minimize, disappear, and display ...

Is there a way to display these panels in a scrollable table layout?

My aim is to replicate this specific styling: https://i.stack.imgur.com/jz5lm.png This type of table shown above is being dynamically imported via Redux: class LocationList extends React.Component { componentDidMount() { this.props.fetchLocations( ...

Tips for implementing an onClick event within a NavBar component in a React application

Embarking on my first React project has been an exciting journey for me. I am relatively new to JavaScript, HTML, CSS, and the world of web app programming. My goal is to showcase some information upon clicking a button. In my main default component, App ...

URL from different domains

Currently, I am attempting to utilize this URL within my javascript code: Below is the snippet of my javascript code: $.ajax({ url: 'http://api.addressify.com.au/address/autoComplete', type: 'GET', crossDomain ...