Performing function in Vue.js when a change occurs

I recently started developing a Vue.js component that includes an input field for users to request a specific credit amount. My current goal is to create a function that will log the input amount to the console in real-time as it's being typed. Ultimately, I plan to dynamically show or hide requested documents based on the user input, without requiring them to click a submit button.

The code snippet below successfully logs the input when the user tabs out of or clicks outside the input field. Here is a snippet from my component.vue file:

<template>
    <div class="col s12 m4">
      <div class="card large">
        <div class="card-content">
          <span class="card-title">Credit Limit Request</span>
          <form action="">
            <div class="input-field">
              <input v-model="creditLimit" v-on:change="logCreditLimit" id="credit-limit-input" type="text">
              <label for="credit-limit-input">Credit Limit Amount</label>
            </div>
          </form>
          <p>1. If requesting $50,000 or more, please attach Current Balance Sheet (less than 1 yr old).</p>
          <p>2. If requesting $250,000 or more, also attach Current Income Statement and Latest Income Tax Return.</p>
        </div>
      </div>    
    </div>
  </div>
</template>

<script>
export default {
  name: 'licenserow',
  data: () => ({
    creditLimit: ""
  }),
  methods: {
    logCreditLimit: function (){
      console.log(this.creditLimit)
    }
  }
}
</script>

When attempting to change methods to computed, the function works but triggers an error stating

Invalid handler for event: change
each time it logs a value.

Answer №1

Utilize the input event.

<input v-model="creditLimit" v-on:input="logCreditLimit" id="credit-limit-input" type="text">

change occurs only when the element loses focus for input elements. The input event triggers each time the text is modified.

Answer №2

It is not necessary to bind the @input event alongside with v-model. Just bind v-model and the model will automatically be updated on input.

new Vue({
  el: '#app',
  data: {
    message: ''
  }
})
<script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a4d2d1c1e4968a908a90">[email protected]</a>/dist/vue.min.js"></script>

<div id="app">
  <input type="text" v-model="message"><br>
  Output: <span>{{ message }}</span>
</div>

If you need to log it on change to console, create a particular watcher:

new Vue({
  el: '#app',
  data: {
    message: ''
  },
  watch: {
    message: function (value) {
      console.log(value) // Log it BEFORE the model is changed
    }
  }
})
<script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="8bfdfeeecbb9a5bfa5bf">[email protected]</a>/dist/vue.min.js"></script>

<div id="app">
  <input type="text" v-model="message"><br>
  Output: <span>{{ message }}</span>
</div>

Answer №3

<input v-model="yourVariableName" @input="yourFunctinNameToBeCall" id="test" type="text">

If you want the function to be triggered when a user selects a value from a dropdown, use @change event.

However, in cases where you need the function to be called when a user presses keys (such as entering values), you should use @click event instead.

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

Failed PHP response when jQuery was called

I'm working on a project that involves two files: one PHP and one HTML. The HTML file acts as the user interface where users input their queries, while the PHP file handles the processing and events before returning the output back to the HTML file. I ...

Retrieving text from Node.js with the help of regular expressions

I need to extract testcase ids from a list of testcases with titles. Each title includes an id and a description. I want to extract only the id. Here are some examples: TC-ABC-98.1.010_1-Verify the layout credit page TC-RegPMP-1.1.001_2-Verify the [MangerD ...

The output of server.address() method in Node.js is ::

My memory serves me right, a few days back it was showing "localhost". I'm puzzled as to what altered server.address().address to now return double colons (::). According to my research, it seems to be returning an IPv6 address (::) because it's ...

One way to filter using a single array

Currently testing some angularJS with this particular example http://www.w3schools.com/angular/tryit.asp?filename=try_ng_filters_filter <ul> <li ng-repeat="x in names | filter : 'i'"> {{ x }} </li> </ul> Is ther ...

Anchor tags created using JQuery will remain on the same page without redirecting

Presented below is the code I have utilized to construct the anchor tag along with its content. $('div#right-slide').html("<a href=\"http://www.XXXXXXXXXXXX.info/limited-specials/\" ><h1 id=\"specials\">Click Here ...

assisting with the transition effect using CSS3, JS, or jQuery

I am looking to alter the background-image of this particular image when transitioning to another one from my images folder, similar to this example. Below is the code that I have: CSS .image { position: relative; overflow: hidden; -webkit-tr ...

Learn how to utilize ajax and jquery to fetch data from an external database without the need for refreshing the page

I'm facing an issue with a small script. I want to query the Content in the database on a simple HTML page without any page refresh. <form method="get" name="formrrv" id="formrrv"> <input type="hidden" name="calculate" value="1 ...

How can it be that "Function" actually functions as a function?

In JavaScript, there exists a function called "Function". When you create an instance of this function, it returns another function: var myfunc = new Function('arg1','arg2','return arg1+arg2'); In the above example, the vari ...

Crafting a template for mixing up images and quotes without any specific connection - here's how!

I came across some interesting templates that can generate random quotes and others that create random pictures. My goal is to develop a template that generates both a random quote and a random picture, similar to this example, without any relation betwee ...

Steps for inserting a menu item into a Material UI Card

Below is an example I'm working with: https://codesandbox.io/s/material-ui-card-styling-example-lcup6?fontsize=14 I am trying to add additional menu options such as Edit and Delete to the three dots menu link, but so far I have not been successful. ...

Handling responses from http requests in Node.js

Below is the code snippet I am working with: exports.post = function(request, response) { var httpRequest = require('request'); var uri = "url.."; httpRequest(uri, function(err, responseHeaders, bodyResponse) { var data = JSON.parse( ...

Is there a way to include a different component without it automatically displaying within a div element?

Is there a way to make the Torrent component render without directly binding it to a DOM element? I am facing an issue with my Torrent Table Component as I want it to be populated with Torrent Components based on API data, but it's not rendering beca ...

Creating distinctively tinted vertices for every subdivision step is simple with the following technique

I am currently working on an application that utilizes different standard geometries, such as box geometry. The application can apply up to 5 levels of subdivision on the original geometry. I am facing challenges in coding a color-coding system for the ver ...

Modifying the default error message in Yup: A step-by-step guide

What is the process for modifying the default error message to a custom error message? Specifically, my custom message. const VALIDATION_SCHEME = Yup.object().shape({ numOne: Yup.Number().required('!'), numTwo: Yup.Number() .r ...

Unexpected mutation of Vuex store state detected

In my view components, I have a mixin that sets the metadata for each page. I'm retrieving the default metadata using Vuex in my store. When applying the mixin to each component, I include the "metadata" data attribute and set its value to the default ...

Using jQuery, remove any white spaces in a textbox that are copied and pasted

There is a textbox for entering order IDs, consisting of 7 digits. Often, when copying and pasting from an email, extra white spaces are unintentionally included leading to validation errors. I am looking for a jQuery script to be implemented in my Layout ...

Steps to creating an Ajax JQuery in WordPress with promises

Currently, I am in the process of developing a custom Wordpress Google Maps plugin. This plugin fetches locations from a database using Ajax and returns an XML file that is then handled by a Javascript script to display them on a Google Map. Everything is ...

EmberJS: Learning how to create a record with a belongsTo relationship

My issue involves using Posts and Comments to explain my problem. In my post_controller, I am trying to create a new record for a comment related to the current post. What is the recommended way to achieve this in Ember? The relationship between Post and ...

Utilize date-fns to style your dates

Struggling to properly format a date using the date-fns library. The example date I'm trying to work with is 2021-09-20T12:12:36.166584+02:00. What am I doing wrong and what is the correct approach? Here's the code snippet I have so far: import ...

- What are the steps to integrate a different JavaScript plugin into a React project?

Lately, I've come across an issue while trying to incorporate a 3rd party plugin into my practice project in Next.js. Considering that I'm fairly new to React, understanding the 'react way' of doing things has proven to be quite challen ...