Home  >  Article  >  Web Front-end  >  How to use v-on:blur to monitor out-of-focus events in Vue

How to use v-on:blur to monitor out-of-focus events in Vue

PHPz
PHPzOriginal
2023-06-11 13:45:072643browse

In Vue, the v-on instruction is a very commonly used instruction, used to bind event listeners to DOM elements, including monitoring out-of-focus events. In this article, we will detail how to use v-on:blur to listen for out-of-focus events.

The basic usage of using v-on:blur to monitor out-of-focus events in Vue is as follows:

<template>
  <div>
    <input type="text" v-on:blur="onBlur">
  </div>
</template>

In the above example, we used the v-on:blur instruction on the input element to Bind a method named onBlur. This method will be called when the input element loses focus.

In Vue, you can also use abbreviations to bind events, as shown below:

<template>
  <div>
    <input type="text" @blur="onBlur">
  </div>
</template>

These two methods are equivalent, and both can bind out-of-focus event listeners.

The following is the detailed code implementation of Demo.

<template>
  <div>
    <h2>Vue中如何使用v-on:blur监听失焦事件</h2>
    <br>
    <label for="username">用户名:</label>
    <input type="text" id="username" v-model="username" @blur="checkUsername">
    <div v-show="showErrorMsg">{{errorMsg}}</div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      username: '',
      showErrorMsg: false,
      errorMsg: ''
    }
  },
  methods: {
    checkUsername() {
      // 这里我们简单判断用户名是否为空
      if (this.username === '') {
        this.showErrorMsg = true
        this.errorMsg = '用户名不能为空'
      } else {
        this.showErrorMsg = false
      }
    }
  }
}
</script>

In the above code, we bound an @blur event to an input element, which called the checkUsername method. In the checkUsername method, we simply determine whether the username is empty, and if it is empty, an error message is displayed.

Through this example, we can see that using v-on:blur to monitor out-of-focus events is very simple. You only need to use the v-on:blur instruction on the element that needs to be bound to the event. Of course, you also need to define the corresponding method in the Vue component to handle the event. This method can be used not only to monitor out-of-focus events, but also to monitor other events, such as click events, keyboard events, etc.

The above is the detailed content of How to use v-on:blur to monitor out-of-focus events in Vue. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn