Learn how to verify changing form inputs with Vue watchers. The challenge of numbers

Currently, I am working on a sum application and encountering some challenges with input validations. I have implemented Watcher to handle the validations, and I am exploring the possibility of adding sound and color feedback for accurate validation.

  1. Repository: https://github.com/RaPzoD1/Divertinumeros
  2. Live Demo:

The following code snippet is used to generate random numbers for the addition operation:

created () {
function getRandomInt (min, max) {
  return Math.floor(Math.random() * (max - min)) + min
}
// console.log(Math.floor(Math.random() * (20 - 2)) + 2)
for (let index = 0; index < 4; index++) {
  const total = getRandomInt(2, 21)
  // this.numRandom.push(getRandomInt(2, 20))
  const numero1 = getRandomInt(1, total)
  const newObj = {
    id: index,
    total,
    numero1,
    numero2: total - numero1
  }
  this.numRandom.push(newObj)
}

The validation process using watchers is as follows:

watch: {
respuesta: {
  handler (newValue, oldValue) {
    const values = Object.values(newValue)
    const operations = [...this.numRandom]
    for (let i = 0; i < values.length; i++) {
      if (i % 2 !== 0) {
        // console.log(operations[i].numero1)
        if (operations[i].numero1 === parseInt(values[i])) {
          console.log('correct', operations[i].numero1, values[i])
          // this.playSuccess()
          // const element = document.getElementById(i)
          // // console.log(element)
          // element.classList.add('correct')
        } else {
          console.log('incorrect', operations[i].numero1, values[i])
          // this.playError()
          // const element = document.getElementById(i)
          // element.classList.add('incorrect')
          // // console.log(element)
        }
      } else {
        // console.log(operations[i].numero2)
        if (operations[i].numero2 === parseInt(values[i])) {
          console.log('correct', operations[i].numero2, values[i])
          // this.playSuccess()
          // const element = document.getElementById(i)
          // element.classList.add('correct')
          // // console.log(element)
        } else {
          console.log('incorrect', operations[i].numero2, values[i])
          // this.playError()
          // const element = document.getElementById(i)
          // // console.log(element)
          // element.classList.add('incorrect')
        }
      }
    }
  }
}

However, the issue arises when the inputs change, causing the watchers to re-validate multiple times.

https://i.stack.imgur.com/6Hbq2.png

Any suggestions on how to improve the validation process?

Answer №1

After reflecting on @Tim's comment, I realized that I was being too greedy by trying to validate multiple fields at the same time. This led me to split the code into smaller parts, resulting in much better performance.

 <section id="suma_libre">
    <div
      class="fila_circulo"
      v-for="numero in numRandom"
      :key="numero.id"
      :id="numero.id"
    >
      <FilaSuma :number="numero"/>
    </div>
  </section>

I decided to change my approach from validating four numbers at once to just one with this revised code:

 data () {
return {
  number1: '',
  number2: '',
  isError: false,
  isSuccess: false
}

},

  watch: {
number1: _.debounce(function (newNumber1) {
  this.number.numero1 === parseInt(newNumber1)
    ? this.playSuccess()
    : this.playError()
}, 500),
number2: _.debounce(function (newNumber2) {
  this.number.numero2 === parseInt(newNumber2)
    ? this.playSuccess()
    : this.playError()
}, 500)

},

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

Setting up environment variables using Azure variables in a Vue project

I am currently working on a Vue project deployed on the Azure DevOps platform. I have set up some variables in the release process and now I want to utilize them within my project. In my company, there is an Angular project that uses env.js with the follo ...

Encountered a problem during the installation of tensorflowjs for node | Received an error: Command failed: node-pre-gyp install

While attempting to install @tensorflow/tfjs-node, I encountered the following error: Command failed: node-pre-gyp install --fallback-to-build. Is there a solution to resolve this issue? Below is the complete log: npm ERR! code 1 npm ERR! path E:\ ...

wiping out a column in Excel spreadsheets with the help of Node.js or its corresponding node modules

I've attempted various approaches without success. Can you provide guidance on deleting and adding columns within an Excel sheet using Node.js? ...

What is the best way to incorporate a URL into your routes?

Within my 10 arrays, each character holds valuable information. My goal is to create a navigation feature that allows me to click on a character and access their specific array data. I am faced with a dilemma regarding dynamic routing - should I extract th ...

Combining HTML, CSS, JAVASCRIPT, and PHP for a seamless web development experience

As a beginner in web development, I have some knowledge of javascript, html, css and am currently delving into php. However, I am struggling to find comprehensive resources that show how to integrate all these languages together. I would greatly appreciat ...

Tips for transferring data from one tab to another tab using Greasemonkey

Is it possible to extract data from a webpage in one tab and then input it into a textarea on a different page opened in a separate browser tab using Javascript and Greasemonkey? ...

Showcasing a dynamically created JSON document on a basic web page

Looking for a solution to display the contents of a result.json file generated by my Java tool on a simple website. I am aware that accessing local files directly with JavaScript is not possible, so seeking alternative methods that do not involve using a w ...

Is there a way to remove the bold styling from text next to JavaScript?

I recently launched a website at www.mvscaccounting.com, and I added a search engine made from javascript at the bottom of the page. Next to it, I wanted to put a "all rights reserved" notice. However, whenever I try to add any text next to the search engi ...

Is there a way to bring in data from a .d.ts file into a .js file that shares its name?

I am in the process of writing JavaScript code and I want to ensure type safety using TypeScript with JSDoc. Since it's more convenient to define types in TypeScript, my intention was to place the type definitions in a .d.ts file alongside my .js fil ...

When incorporating Vue as an npm package, a Vue 3 app may inadvertently clear the mounted element upon initialization

I have a straightforward Vue 3 application that is working perfectly fine when I include Vue as a script, as shown in the code snippet below. However, I need to integrate it with webpack by including it as an npm package. When I do this, the app loads but ...

Understanding Node.JS: A Dive into Key Concepts

Forgive my lack of knowledge, but I'm really trying to grasp the differences between Node.js and Backbone.js. I believe I'm getting there, but could someone confirm this or guide me in the right direction? Node.js is a platform that can handle H ...

Returning Props in Dynamic Components with Vue 3

Exploring the capabilities of Vue3's Dynamic Component <component>, I am currently working with this setup: Component 1: <template> <div> <h1> Name Input: </h2> <Input :model="props.name" /> ...

A comprehensive guide on effectively monitoring Form Abandonment in Google Analytics using jQuery or JavaScript

Is it possible to accurately track "Form Abandonment" in Google Analytics using jQuery or JavaScript? This method can help generate reports that display how far users progress through form filling before exiting or failing to submit. Are there more effect ...

Encountered an issue when executing npm command due to a permission error

My hosting is on a digitalocean droplet and my website is built in Laravel. When I try to run the following command, I encounter the attached error. The command that I am running as a root user is: npm run dev Can anyone help me with this issue? Thank y ...

The tab indicator in Material-UI fails to update when the back button is clicked

My code is currently functioning well: The tab indicator moves according to the URL of my tab. However, there is a peculiar issue that arises when the back button of the browser is pressed - the URL changes but the indicator remains on the same tab as befo ...

The length of the LinearProgress bar does not match the length of the navbar

Utilizing the LinearProgress component from Material UI, I created a customized ColoredLinearProgress to alter its color: import React, { Component } from 'react'; import { withStyles } from '@material-ui/core/styles'; import { LinearP ...

Exploring the realms of Django Administrator with external JavaScript integration

Currently, I am working with django 2.0 that includes jquery 2.2.3. My goal is to implement the ImageViewer Javascript app (https://github.com/s-yadav/ImageViewer) on one of my admin pages. I have added the necessary js and css files to the Media class wit ...

The steps to properly load "child.vue" into the correct position within "parent.vue" are as follows

Currently I am developing a single page web application using Vue.js. This app consists of 4 "page.vue" files, each with a right and left child .vue component nested inside. For instance, the Page1.vue file is structured as follows (omitting style and scr ...

What is preventing me from using AJAX to input data into sqlite?

Implementing a local save feature in my Web App is proving to be quite challenging. Every time I attempt to send data in any form, I consistently encounter the following error: A builtins.TypeError occurs, followed by a stack trace in /SaveFile and jquery ...

What is the method for formatting within the <textarea> element?

While working on developing a comment system, I recently made the discovery that text areas cannot be formatted to retain paragraphs, line breaks, etc. This was particularly noticeable when comparing sites like StackOverflow, which uses a text editor inste ...