Get value from input using on change in Vue

featured Image

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

Related Posts

featured Image

How to add common header and footer in vuejs.

Here, in this article, we will learn how to add a common header and footer component in our vuejs application. In general, we always have the same header and footer…

Read more
featured Image

How to call a function in VUE template?

Here, we will learn on how to call a function in vue template. First, we have to define the function in the methods. and then we can use an event…

Read more
featured Image

How to redirect to external url in vue

Here, we will learn how to redirect to an external URL in vuejs application. Page Navigation is one of the basic features of a website. It helps us to navigate…

Read more

Leave a Reply

Your email address will not be published. Required fields are marked *