Get value from input using on change in Vue

In this post, we will see how we can get the value from an input field on change using @input in Vue.

In Vue, we can use the two-way binding of an input field using the v-model directive. For example

<template>
  <div id="app">
    <input type="text" placeholder="Enter name" v-model="name" />
    <div>
      {{ name }}
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      name: "",
    };
  },
};
</script>

This will synchronously get the data from the input field and store it in the ‘name‘ data property. So every time the value changes in the input field, the ‘name‘ model keeps track of it.

However, if you want to trigger a method depending on the changes in the input value, then we can use the v-on directive with the input event.

Read How to set a default value to input with a v-model in Vue

Get user input value on change in Vue

In Vue, the v-on directive helps to listen to user input events such as clicks and mouse events etc.

So to get the value on change we will use the v-on:input or the shorthand @input . This will help us to call a function each time the user changes any value in the input field.

Let’s see with an example, how we can run a function to get the data from the input.

<template>
  <div id="app">
    <input type="text" @input="upCaseWord" placeholder="Enter name" />
    <div>
      {{ name }}
    </div>
  </div>
</template>

<script>
export default {
  name: "App",
  data() {
    return {
      name: "",
    };
  },
  methods: {
    upCaseWord(event) {
      this.name = event.target.value.toUpperCase();
    },
  },
};
</script>

In our example, we have added @input event, which will run the function upCaseWord() when the user makes changes in the input field.

The upCaseWord() function gets the input value from the input and convert it to uppercase and assigns it to the data property ‘name‘.

And using the event, we can pass input text on change to a Vue method. And here, we have used event.target.value to get the value.

Demo Code

Get input value on change in Vue

Edit 4o1erz

Related Topics:

How to set a default value to input with a v-model in Vue

Scroll to Top