Using Vue.js to reset a timer with props

<template>
    <span>{{time}}</span>
</template>
<script>
  export default {
    name: 'Timer',
    data () {
      return {
        time: 0
      }
    },
    mounted () {
      setInterval(() => {
        ++this.time
      }, 1000)
    }
  }
</script>

The main

<template>
  <div class="tetris">
    <timer></timer>
  </div>
</template>
<script>
  import Timer from './Timer'
  export default {
    name: 'Game',
    components: {
      Timer: Timer
    },
   }

In this context, what would be the optimal way to restart the timer from the parent component? Maybe passing a prop like "start", "stop", or "reset" without emitting events to prevent all instances of the timer from resetting simultaneously?

Answer №1

Utilizing a prop and observing it can serve as an effective method for handling the transmission of events from the parent component to the child component. It is recommended to use props for parent-to-child communication and emitting events for child-to-parent communication when passing data between these components.

While there are various libraries that facilitate inter-component communication, adhering to this approach remains valid in Vue.js development.

Answer №2

Instead of increasing the timer within the child component, a better approach is to manage it in the parent component's data and increment it there. You can then pass the timer value to the child component using props. Additionally, you have the flexibility to reset the timer in the parent component at any point. Feel free to try out the code snippet below to observe the results:

Child Component Code

<template>
<span>{{timer}}</span>
 </template>
 <script>
 export default {
  name: 'Timer',
   data () {
  return {

     }
   },
      props:{timer:Number},
      mounted() {

        }
   }
  </script>

Parent Component Code

<script>
  import Timer from './Timer'
  export default {
    name: 'Game',
    data(){
      return {
        timerInit:0
      },
    components: {
      Timer: Timer
    },
    mounted(){
      setInterval(()=>{
        ++this.timerInit ;
        console.log(this.timerInit);
      },1000)
    },
 methods:{
      clickHandler(){
        this.timerInit = 0 ;
        console.log(this.timerInit);
      }
    }

   }
<template>
  <div class="tetris">
    <timer:timer="timerInit"/>
    <button @click="clickHandler">reset</button>
  </div>
</template>

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

How can I specify the specific function for AJAX to send a POST request to if there are two functions in one PHP file?

Looking for guidance on how to set up ajax to post to the function named upvoteImage() in a php file that contains both upvote and downvote functions. As a beginner in ajax, I'm facing some challenges in making it work. Javascript file $('.arro ...

Arrange a List in immutable.js by using an array of index values

My scenario involves working with an Immutable list to populate a drag and drop feature. The list items do not have any ids, only indices when mapped through. const list = Immutable.List([{"alias":"cat"},{"alias":"dog"},{"alias":"rat"}]) Upon dragEnd, I ...

Error: The current component does not have a template or render function specified. Check the <App>

I am a beginner in Vue js and I am facing an issue while running my application. It is showing an empty page with the error message: Component is missing template or render function. at <App>. Additionally, there is also a warning from Vue Router sa ...

What is the reason for xhr.response being set to null whenever there is a warning in my PHP code?

In order to clarify, it's important to note that the .php files belong to my professor and should not be altered. The issue arises from the fact that $VALORES on line 186 is uninitialized, and I have already reported this to my professor. Below is th ...

Tips for verifying a javascript validation using radio and checkbox buttons

While working on an online store, I have encountered the need to verify whether a user has selected a payment option and agreed to the CGU rules. Here is the HTML code snippet I am using: <div id="choixPaiement"> <div class="choixDuReg ...

If the checkbox is selected, retrieve the product name and price and store them in an array

If the checkbox is checked, I want to retrieve the service name and its price in an array. To get the values of the selected items (i.e. service name and its price in an array), please explain how I can achieve this. $(document).on('click', &apos ...

When dynamically binding onclick events within a for loop, all buttons end up with the same value

I'm currently working on a project where I am creating buttons dynamically and assigning an alert function for each one upon a click event. Here is the JavaScript function: function GenerateButtons(tabObj) { for (var t = 0; t < tabObj.views.vie ...

Experiencing a console error which reads: "SyntaxError: Missing ) after argument list."

While working on configuring a new React CSR app and incorporating some boilerplate libraries, I encountered an error in the console: Uncaught SyntaxError: missing ) after argument list (at @emotion_react_macro.js?v=30f6ea37:29894:134) I am hesitant to ma ...

Error: The function 'check' is not defined and cannot be called when the 'on

My aim is to display the "expandrepeat" div when a specific select option is chosen. Unfortunately, the code below doesn't seem to be working as intended: <script> window.check=function(elem) { if (elem.selectedIndex == 1) { documen ...

Creating pathways in AJAX with Rails

Issue at hand: undefined variable article_id. The objective: Setting up the correct route for AJAX and Rails. What I require: The format articles/1/comments/2. Main goal: To specifically load comment through AJAX, not article. In the current AJAX scrip ...

The csurf token in Node.js consistently shows as invalid

Upon installing the csurf package on my Node.js Express application, I encountered an issue with validating the CSRF token. Despite properly displaying the token in the form as name="_csrf" with a hash value set using req.csrfToken(), I consistently receiv ...

Transferring state to a nested child component within a parent component's child

Currently, I am in the process of developing a KanBan application using ReactJS. My main goal is to propagate the state from a parent component to the farthest child component in the hierarchy. Within my main App component, there exists a Column component, ...

"Learn how to seamlessly submit a form and display the results without the need to refresh the

Here is the form and result div: <form action="result.php"> <input type="checkbox" name="number[]" value="11" /> <input type="checkbox" name="number[]" value="12" /> <input type="checkbox" name="number[]" value="13" /> <input t ...

Simply click on the image to open it in a lightbox view with a thumbnail using jQuery

I have implemented a feature using fancybox to display images in a lightbox with thumbnail images. My requirement is that when a user clicks on an image, the clicked image should be displayed first in the lightbox and the rest of the images should not be s ...

How can I retrieve the chosen value of JQuery Chosen from the backend?

Is it possible to dynamically populate a select value from C# code using jQuery Chosen? I have successfully populated my select, but the issue is that it always returns the first item instead of the selected one. Here is how my select is declared: <s ...

The search button is malfunctioning after I submit search data and generate dynamic HTML using axios

When a user clicks on the search button, I retrieve the input value and then use axios to send a GET request with the search data. Everything works fine, but when I query the database and dynamically create data from the mongoose data, the page reloads w ...

Tips for rendering a component upon the page loading in reactjs

I'm really impressed with the work done here. I recently started working with reactJS and am currently using it to create the view layer for my application. My goal is to create a header that displays a message 3 seconds after the page has completely ...

How can you use Dart to uncover the content within an H1 element on an HTML webpage?

I'm currently self-teaching mobile development with Dart and Flutter, and my current project involves connecting a mobile app to a website. I want to extract the text from an H1 tag that is loaded through JavaScript on the website and display it in th ...

After 30 to 80 touches, the movement starts to lag and an error appears in the console

Error Details: [Intervention] A touchend event cancellation attempt was ignored due to cancelable=false, likely because scrolling is in progress and cannot be stopped. preventDefault @ jquery.min.js:2 (anonymous) @ number_grid_game.php:239 each @ ...

Connecting a Node.js Redis client to a Redis cloud server: Step-by-step guide

const redis = require('redis'); const client = redis.createClient({ host: 'redis-19606.redislabs.com', port: 19606, password: 'password' }); client.on('ready', () => { console.log('redis is connecte ...