Vue.js: Calling function on change

Viewed 34934

I'm building a component in Vue.js. I have an input on the page where the user can request a certain credit amount. Currently, I'm trying to make a function that will log the input amount to the console, as I type it in. (Eventually, I'm going to show/hide the requested documents based on the user input. I don't want them to have to click a submit button.)

The code below logs it when I tab/click out of the input field. Here's my component.vue:

<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>

If I change methods to computed, it works - but I get an error saying Invalid handler for event: change every time it logs the value.

3 Answers

Binding @input event alongside with v-model is unnecessary. Just bind v-model and thats all. Model is automatically updated on input event.

new Vue({
  el: '#app',
  data: {
    message: ''
  }
})
<script src="https://unpkg.com/vue@2.4.4/dist/vue.min.js"></script>

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

And if you need log it on change to console, create particular watcher:

new Vue({
  el: '#app',
  data: {
    message: ''
  },
  watch: {
    message: function (value) {
      console.log(value) // log it BEFORE model is changed
    }
  }
})
<script src="https://unpkg.com/vue@2.4.4/dist/vue.min.js"></script>

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

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

You can use @change to it trigger the function when is done Ex- Select a value from drop down

But here you need to call the function when pressing keys (enter values). So use @click in such cases

Related