Enhance your Vue.js experience with an improved method for monitoring values

My setup involves Vue CLI 3.11 (based on Node.js 12.10) and Google Chrome.

I am trying to create a syntax that can bypass the watch function under specific conditions. However, I am struggling because Vue.js handles value changes differently compared to JavaScript.

For instance, in the following code snippet, the value is always logged because the "valuelock" is consistently false in the watch function.

<script>
export default {
  name: 'app',
  data(){
    return {
      v: null,
      valuelock: false
    };
  },
  mounted(){
    this.valuelock = true;
    this.v = localStorage.getItem("value");
    if(this.v === null) this.v = 0;
    this.valuelock = false;
  },
  watch:{
    v(nv){
      console.log("watch:"+this.valuelock);
      if(this.valuelock === false){
        localStorage.setItem("value", nv);
      }
    }
  }
}
</script>

Currently, I am using setTimeout() to handle the delay, but I am unsure if this is the best approach.

  mounted(){
    this.valuelock = true;
    this.v = localStorage.getItem("value");
    if(this.v === null) this.v = 0;

    const t = this;
    setTimeout(()=>{
      t.valuelock = false;
    }, 0);
  },

If you have a more efficient method to manage real-time value changes in Vue.js, please share your insights!

Answer №1

Instead of using watch, you can achieve the same functionality by utilizing a computed property along with get and set to intercept changes.

export default {
  name: 'app',

  data () {
    return {
      rawValue: null
    }
  },

  computed: {
    value: {
      get () {
        return this.rawValue
      },

      set (value) {
        localStorage.setItem('value', value)
        this.rawValue = value
      }
    }
  },

  mounted () {
    this.rawValue = +localStorage.getItem('value') || 0
  }
}

Instead of accessing rawValue, the remaining code should now reference

value</code to ensure that changes are properly saved.</p>

<p>Additionally, I've adjusted the reading of the value from <code>localStorage
to
+localStorage.getItem('value') || 0
. This assumes that you intend to store a number, as localStorage stores values as strings.

You can also incorporate the code from the mounted function into the data function. For example:

data () {
  return {
    rawValue: +localStorage.getItem('value') || 0
  }
}

This approach can be applied to your original code as well, offering an alternative solution to the problem. By setting the initial value from localStorage within the data function, it avoids triggering the need for a watch.

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

What methods can I employ in Javascript to automatically display search results obtained from multiple HTTP search queries?

In my tampermonkey script, I am attempting to process an array of names by performing a search and printing the page for each one. The script runs automatically upon loading the page, hence the necessity of the if statement. $(document).ready(function(){ ...

Tips for toggling password visibility by clicking outside a password field

As I work on creating a password field that allows users to toggle the visibility of their password by clicking an eye icon, I am facing a challenge. I want the password to be hidden automatically when the user clicks outside the field, which requires a co ...

Concealing the print option while utilizing PDFObject in conjunction with PDF.js

When displaying a file using pdf.js, I encountered issues with the print button and other functionalities. I was able to hide the buttons using CSS for Chrome, but not for Internet Explorer, where I had to resort to using JavaScript. While the JavaScript ...

How to efficiently transfer data between Node and Angular 7 using Electron

After setting up an Angular 7 application running on http://localhost:4200, I developed a Node JS application responsible for authenticating users on Facebook, accessible at http://localhost:3000. The callback redirection functions correctly within the No ...

Monitoring of access controls on Safari during uploads to S3

Safari 10.1.2 Encountering an issue intermittently while attempting to upload PDF files to S3 using a signed request with the Node aws-sdk. Despite working smoothly 90% of the time, have been pulling my hair out trying to resolve this problem. Could it be ...

Show User Input as a dynamic tool-tip in Highcharts

Is it possible to gather 12 user inputs through multiple text areas in a popup dialog box, and then use these inputs as tooltips for various points on a graph like the one shown in this demo: http://www.highcharts.com/demo/line-labels? I haven't found ...

Can an iframe be replicated?

How can I retrieve the content of a specific webpage, such as http://google.com, and dynamically insert it into the current document while preserving styles, scripts, and other elements just like an iframe does? Additionally, I want to ensure that the sty ...

transform the outcome of a $lookup operation into an object rather than an array

When performing a $lookup from a _id, the result is always 1 document. This means that I would like the result to be an object instead of an array with one item. let query = mongoose.model('Discipline').aggregate([ { $match: { ...

How can I avoid duplicating code in HTML? I find myself utilizing the Bootstrap 4 collapse feature around 20 times on a single page

<div class="card" style> <div class="card-header" id="headingOne"> <h5 class="mb-0"> <button class="btn btn-link" data-toggle="collapse" data-target="#collapseOne" aria- expanded="true" aria-controls="collapseO ...

When attempting to incorporate Jasmine into my current AngularJS/Bootstrap project, I encountered the error message stating

Currently, I am working on a group project that requires test coverage. The project utilizes npm and angularJS. To kick things off, I performed an npm install for jquery, jasmine, and angular-mocks. Since I'm relatively new to testing, I decided to st ...

Experimenting with axios.create() instance using jest

I have attempted multiple solutions for this task. I am trying to test an axios instance API call without using any libraries like jest-axios-mock, moaxios, or msw. I believe it is possible, as I have successfully tested simple axios calls (axios.get / axi ...

Display radio buttons depending on the selections made in the dropdown menu

I currently have a select box that displays another select box when the options change. Everything is working fine, but I would like to replace the second select box with radio buttons instead. Can anyone assist me with this? .sub{display:none;} <sc ...

Unable to retrieve information from JSON file utilizing AngularJS version 1.6

I'm having trouble retrieving data from my JSON file using AngularJs 1.6 myApp.controller("homeCtrl", function($scope, $http) { $scope.Data = []; var getJsonData = function() { $http.get('contactlist.json').then(func ...

Begin a fresh page within a separate window, proceed to print the contents, and subsequently close the window

I am facing some difficulties with this code. I am attempting to use the "onClick" function to change the image once it is clicked, open a new page in a new window, print the newly opened window, and then close it. The issue I am encountering is that while ...

Values do not appear as expected post PDF conversion using wkhtmltopdf

Currently, I am updating certain values within my HTML page by following this process: The function: function modifyContent(){ var newTitle = document.getElementById('myTextField1').value; if( newTitle.length==0 ){ alert('Plea ...

Setting up types for variables in Angular 2 componentsHere is an

I have a model that consists of multiple properties, and I aim to set all these properties with a default value of either empty or null. Here is an example of my Model: export class MyModel { name: string; jerseyNumber: number; etc... } In m ...

When a base html tag is dynamically added, the browser mistakenly loads assets twice

When managing relative paths on a website, I utilize the <base> tag within the <head> section of each page. Although all resources loaded via relative-like paths in the documents are displayed correctly, my observations show that browsers such ...

JavaScript: Different ways to utilize the reduce method

Creating an array for search purposes based on a string like BBC Sport, the desired output array will be: [ 'BBC', 'BB', 'B', 'Sport', 'Spor', 'Spo', 'Sp', 'S' ] An implement ...

Utilize a single JavaScript file to handle various views without encountering errors due to undefined functions

My backend editing requires a single JS file. However, I face the challenge of needing different sets of methods for view A and view B — never both at the same time. To streamline this process, I combined all the jQuery functions for both views into one ...

Utilizing the zIndex property on a map label does not produce any impact when combined with a GeoJSON layer

Utilizing the Google map label tool, I am trying to showcase certain property from GeoJSON data on a GeoJSON layer. However, the issue arises as the layer has a dark color and the label is appearing blurry behind the GeoJSON data layer. Despite attempting ...