The key to the method in vue.js watch object functioning correctly lies in implementing closure within it for optimal performance

index.html

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>VueJS</title>
    <script src="vue.js"></script>
  </head>
  <body>
    <div id="app">
      <button @click="counter++">increase</button>
      <button @click="counter--">decrease</button>
      <p>Counter: {{counter}}</p>
      <p>Result: {{ result() }} | {{ output }}</p>
    </div>
  </body>
</html>

<script src="app.js"></script>


app.js

new Vue({
  el: "#app",
  data: {
  counter: 0
  },
  computed: {
    output() {
      console.log('Computed!')
      return this.counter > 5 ? 'Greater than 5' : 'Smaller than 5'
    }
  },
  watch: {
    counter(value) {
      var vm = this;
      setTimeout(() => {
        vm.counter = 0;
      }, 2000)
    }
  },
  methods: {
    result() {
      console.log('Method!')
      return this.counter > 5 ? 'Greater than 5' : 'Smaller than 5'
    }
  }
})

hey, I'm sharing some code here.

Just a heads up, when the value of the counter changes, the watch property is triggered and after 2 seconds, the counter is reset to 0.

This script is flawless! but there's one thing that confuses me about the watch property. why does the counter method in the watch property only work when using the closure feature?

counter(value) {
  var vm = this;
  setTimeout(() => {
    vm.counter = 0;
  }, 2000)
}

this does the trick!

counter(value) {
  setTimeout(() => {
    this.counter = 0;
  }, 2000)
}

but this doesn't do the job! (counter remains unchanged even after 2 sec)

what could be causing this situation?

Answer №1

Issue has been resolved and it was my mistake. Big thanks to Daniel for the help! As I am new here, I am unsure if this is the correct way to conclude this question...

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

I'm trying to understand a JSON object that has multiple key names pointing to a single value. How can I properly interpret this in

Encountering an object with a strange key. const obj = { formValues: { 'TOTAL;_null_;_null_;3;_null_': "100" 'billing;_null_;_null_;1;_null_': "Y" 'billing;_null_;_null_;2;_null_': "Y" 'billi ...

What is the best way to segregate Express routes from server.js?

I've been closely following a Vue SSR guide on GitHub and noticed that the author has organized their Express routes within a file named server.js. For better organization, I prefer to keep my Express routes in a file called router.express.js located ...

"Contrary to the body onload event, the window.onload event does not

So, this is my first time asking a question here. Hopefully I am providing all the necessary information. My issue is with using window.onload to display a page scripted in the head of my HTML code with type="text/view". When I tried putting the code in t ...

What is the proper placement for index.html <head/> class helper functions within a ReactJS Component?

My custom helper functions are stored in a JavaScript file called classie.js: ( function( window ) { 'use strict'; function classReg( className ) { return new RegExp("(^|\\s+)" + className + "(\\s+|$)"); } var hasClass, ...

The issue with ag-grid not displaying data when the column configurations are changed dynamically

I have been working with ag grid to display data in my component. I am fetching data through an API call and dynamically extracting the column names from the response to pass this information to the child component for display. However, the data is not sho ...

Best Practices for Managing Asynchronous Updates in Angular Controllers

Let me explain my current setup -- I have a controller that utilizes a service to perform some tasks and then fetches data asynchronously. Right now, the data is returned after a timeout, but ideally it would involve more complex operations: This is how m ...

The jQuery toggleClass() function is not being applied successfully to content that is dynamically generated from

I've created an awesome collection of CSS-generated cards containing icons and text with a cool animation that expands upon tapping to reveal more icons and options. I carefully crafted the list to look and behave exactly how I wanted it to. But now, ...

Is there a way to programmatically click on a link within the first [td] element based on the status of the last [td] element in the same [tr] using codeceptjs/javascript?

The anticipated outcome: Pick a random assignment from the table that has the status "Not start". Below is the table provided: <table id="table1"> <tbody> <tr class="odd1"> <td> < ...

Tips for embedding a React JS variable into an HTML element

When working in my React JS project, I encountered the issue where I needed to dynamically create a link with a specific ID. The code I am trying to render is as follows: <a href="http://localhost/PHP-React-Demo/update_record.html?id="{stud.id}>//th ...

Only encountering a 401 error with API requests in the production environment

Having an issue where Laravel 6 API requests are functioning smoothly on the local server, but encountering a 401 error on the remote server. Both servers are nginx-driven with php-fpm setup. Authentication is done using Laravel Passport ...

Node.js with Koa: Discontinuation of generator usage on the next step

I am working with a custom object in which I pass a parameter, and then I need to search for all documents in my collection and process them. Here is the code for my custom object: var db = require('../lib/db'); function Widget(n,l,c,o,t,p) { ...

When I hover over div 1, I am attempting to conceal it and reveal div 2 in its place

I need help with a CSS issue involving hiding one div on mouse hover and showing another instead. I attempted to achieve this using pure CSS, but both divs end up hidden. Would jQuery be necessary for this task? Below is the CSS/HTML code I wrote: .r ...

The v-navigation-drawer component in Vuetify 2 is not reappearing after setting dialog to false

I am utilizing the navigation drawer to display my data list in a dialog box. Everything works fine when I initially open it, however, upon reopening the dialog, the entire navigation drawer vanishes. The data GET operation is functioning correctly with no ...

Angular multiple checkbox array iteration in ng-repeat

I am currently working on a form using Angular and facing a challenge with a specific section. Within the form, there is a 'Divisions' segment that includes a list of checkboxes generated dynamically from an API call. Users are required to selec ...

Steps to Change the Background Color to White in a Dropdown menu

Hello everyone! I'm currently using this codepen example on my website. My query is regarding the fifth panel - is it possible to change the color of the drop-down box when clicking on it? Here's a snippet of the HTML: <link href='https: ...

Display a toasted notification following a refresh

After reloading the page, I want to display a toast notification confirming that the file has been uploaded. Here is my current code: _fileUploads.delete = function(reload_on_return) { var filtered = root.fileUploads().filter(_ => _._id() == _fileUpl ...

The error message "ReferenceError: process is not defined" is caused by a module located at "../../node_modules/graphql/jsutils/instanceOf

While working on my latest project, an Instagram clone, I made use of GraphQL subscriptions to implement the functionality for liking/unliking posts. For my client, I utilized npx create-react-app to set up the front end and express for the server. Within ...

Insert discover within the tube

Can I modify the following code to add a pipe before the subscribe method that performs the find operation, so that only one panel is returned by the subscription? await this.panelService.getActivePanels() .pipe( map(activePanels => active ...

React 16 is encountering a discrepancy due to the absence of the data-reactroot attribute

As I was in the midst of updating some apps to React 16, I couldn't help but notice that the data-reactroot attribute is no longer present on the main root element. Although not a critical issue, it seems like we had certain code and styles that reli ...

Exploring the world of React.js through the exchange and manipulation of data

Essentially, I am utilizing refs to obtain component dimensions in the componentDidMount() lifecycle method. When I log this information, I can see the width that I desire (refer to code). However, when I attempt to access and log this data in the render() ...