What is the best way to implement a timeout feature in Vue after a button is clicked?

I am struggling to make the background color return to its default after 3 seconds using the setTimeout method. How can I adjust my code to achieve this successfully, or should I consider using a transition instead?

<div id="exercise">

    <div>
      <p>Current Value: {{ value }}</p>
      <button @click="value += 5(); red();" :style="{ 'background-color': color }">Add 5</button>
      <button @click="value += 1">Add 1</button>
      <p>{{ result }}</p>
    </div>

    <div>
      <input type="text" v-model="timer">
      <p>{{ value }}</p>
    </div> 
  </div>
new Vue({
  el: "#exercise",
  data: {
    value: 0,
    timer: 1000,
    color:'pink',


  },
  methods:{
  red() {
   this.color = "red";
setTimeout(function() {
        this.red = 0;
      }, 1000); 
  }
  },
  computed: {
    result: function() {
      return this.value >= 37 ? "Not there yet" : "done";
    }
  },
  watch: {
    result: function(value) {
      var vm = this;
      console.log(value);
      setTimeout(function() {
        vm.value = 0;
      }, 5000);
    }
  } 
});

Answer №1

Consider using an arrow function with setTimeout to ensure that the correct context of this is maintained. Arrow functions utilize lexical scoping and automatically bind this to the inner function:

new Vue({
  el: "#exercise",
  data: {
    value: 0,
    timer: 1000,
    color:'pink',


  },
  methods:{
  red() {
   this.color = "red";
setTimeout(() => {
        this.color = "";
      }, 1000); 
  }
  },
  computed: {
    result: function() {
      return this.value >= 37 ? "Not there yet" : "done";
    }
  },
  watch: {
    result: function(value) {
      var vm = this;
      console.log(value);
      setTimeout(function() {
        vm.value = 0;
      }, 5000);
    }
  } 
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="exercise">
    <div>
      <p>Current Value: {{ value }}</p>
      <button @click="red();" :style="{ 'background-color': color }">Add 5</button>
      <button @click="value += 1">Add 1</button>
      <p>{{ this.result }}</p>
    </div>

    <div>
      <input type="text" v-model="timer">
      <p>{{ value }}</p>
    </div> 
  </div>

(Furthermore, in your setTimeout function, make sure you are assigning this.color = "" instead of this.red = 0 :D

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

Discovering the bound ASP.NET AJAX event handlers for a specific DOM element

I am currently working on customizing a pre-existing ASP.NET 3.5 AJAX web application, specifically SharePoint 2010. Unfortunately, I do not have the ability to modify the source code. My task involves adding a click event handler to act as the first even ...

Is there a way to set up one function that can be used across different HTML buttons?

As a newcomer to JS, I've taken on the challenge of creating a size comparison tool for practice. In my HTML file, I have multiple buttons representing different US sizes that should display the corresponding UK, EU, and CM size when clicked inside a ...

Troubleshooting Port Issue When Deploying Node/Sequelize Application on Heroku

I am in the process of developing a Node/Postgres application that will be deployed to Heroku. During my attempts to launch the app in a production environment, I encountered a timeout error. According to Heroku, this error is likely due to database or por ...

Learn a valuable trick to activate CSS animation using a button - simply click on the button and watch the animation start over each time

I already know how to do this once. However, I would like the animation to restart or begin again when the user clicks on it a second time. Here is what I have: function animation() { document.getElementById('ExampleButton').className = &apo ...

The transitions in Vue do not seem to be functioning properly when used with router-link and $router

I have the following structure in my App.vue file: <script setup> import { RouterView } from "vue-router"; </script> <template> <RouterView v-slot="{ Component }"> <transition :name="fade" mod ...

Guide on creating a menu that remains open continuously through mouse hovering until the user chooses an option from the menu

I have a unique scenario where I am working with two images. When the mouse hovers over each image, two corresponding menu bars appear. However, the issue is that when the mouse moves away from the images, the menu disappears. Any suggestions on how to im ...

Updating the state after receiving API results asynchronously following a function call

I am attempting to update the state asynchronously when my fetchWeather function is executed from my WeatherProvider component, which calls an axios request to a weather API. The result of this request should be mapped to a forecast variable within the fet ...

Tips for consolidating multiple JavaScript files from various directories into one single file?

I am currently working on a project that involves multiple JavaScript files stored in various folders. My goal is to combine them all into a master.js file. The project structure looks like this: /dist/js/master.js <-- Output file /src/bootstrap-untou ...

Exploring the Depths of React Routing: The Power

I'm currently diving into React and trying to figure out how to create dynamic routes similar to partial pages in Angular. Here is my main App component: import React from 'react'; import Header from '../common/Header'; export d ...

What is the best method for displaying multiple slices within an SVG circle?

I'm currently working on a project involving a reactJS application. The goal is to display an svg circle that, when clicked, divides into n equal slices. I have successfully generated the individual slices with the following code: renderSlices = () ...

The utilization of 'new' is not allowed with an expression that does not have a call or construct signature in TypeScript

While searching for a solution, I stumbled upon this link which unfortunately did not provide the answer I was looking for: Cannot use 'new' with an expression whose type lacks a call or construct signature I am facing a similar issue. In my JavaS ...

Guide to implementing controllers in vuejs2

Hey there, I recently started using vuejs2 with a project that is based on laravel backend. In my vuejs2 project, I wrote the following code in the file routes.js export default new VueRouter({ routes: [{ path: '/test', component: ...

Constructor-generated element doesn't reflect changes upon component re-rendering

Why doesn't the <select> I create in the constructor update correctly when I select a different flavor? The other select and text update, but not this one. class ConstructorComponent extends React.Component { constructor() { super(); ...

Is it possible for my Java Applets to be compatible with Chrome 45?

Our web application utilizes three Java Applets for various functions. We are aware that Chrome 45 will no longer support NPAPI. Upon visiting Oracle's page, it is stated that Java Plugin depends on NPAPI. I have tested my Applets on Chrome 43 and 4 ...

Arranging elements in two arrays in either ascending or descending order

Looking to implement sorting functionality for the "fuel.name" value within this array... const orders = [ { "_id":"5d14a31490fb1e0012a3d2d8-1", "orderId":"0JL5ORM0JT-1", "created":"2019-06-27T11:05:56.377Z", "createdDate":"2019-06-2 ...

Unable to locate module: Unable to locate the file './Header.module.scss' in '/vercel/path0/components/Header'

I encountered an error while attempting to deploy my next application on Vercel. I have thoroughly reviewed my imports, but I am unable to pinpoint the issue. Module not found: Can't resolve './Header.module.scss' in '/vercel/path0/comp ...

Can you provide instructions on how to configure the date format for the p:calendar component using client-side methods

Let's discuss the current scenario at hand. I have a JSF page where a date is displayed in the following manner: <h:outputText value="#{bean[date]}" > <f:convertDateTime pattern="#{Const.CALENDAR_PATTERN}"/> // featuring a ca ...

Guide on transforming a select dropdown into a ul dropdown

I am attempting to transform my select dropdown menu into an unordered list (ul) in order to create a bootstrap button that will display the ul, allowing the list items to function as options. <select id="sortField" onchange="refreshPage('{$pageBa ...

Tips for extracting data from cells within an HTML table using JavaScript

I am looking to extract the values from a cell of an HTML table in order to store them in a MySQL table using PHP. I prefer to utilize JavaScript instead of jQuery. I have assigned a unique ID to each TR based on the ID field in the MySQL table. Additiona ...

Ways to incorporate a php file based on the user's selection

I have numerous div elements, possibly a dozen or two, such as... <div class="mydivs" id="firstdiv"></div> <div class="mydivs" id="seconddiv"></div> <div class="mydivs" id="thirddiv"></div> <div class="mydivs" id="fo ...