@blur事件
时间: 2025-04-27 22:15:15 浏览: 26
### 关于 `@blur` 事件的使用方法
在 Vue.js 中,`@blur` 事件用于监听 HTML 元素失去焦点的情况。当用户点击页面上的其他位置或切换到另一个元素时,会触发该事件。
#### 基本语法
```html
<input type="text" @blur="handleBlur">
```
在此示例中,每当 `<input>` 元素失去焦点时就会调用名为 `handleBlur` 的函数[^2]。
#### 结合修饰符使用
可以将 `.prevent`, `.stop` 等修饰符与 `@blur` 联合起来增强功能:
- 阻止表单提交中的默认行为:
```html
<form>
<input type="email" @blur.prevent="validateEmail"/>
</form>
```
- 防止事件冒泡至父级组件:
```html
<div id="parent-element">
<button @click="doSomething">@blur won't bubble up</button>
<input type="password" @blur.stop="onBlurHandler"/>
</div>
```
这些例子展示了如何利用不同的修饰符来控制特定场景下的交互逻辑[^1]。
#### 实际应用场景
假设有一个登录界面,在密码字段上应用了 `@blur` 来检测并提示错误信息:
```javascript
methods: {
checkPassword() {
const passwordInput = this.$refs.password;
if (!this.isValidPassword(passwordInput.value)) {
alert('Invalid Password!');
// 手动设置 focus 返回给输入框以便修正
setTimeout(() => { passwordInput.focus(); },0);
}
},
isValidPassword(pwd){
return pwd.length >=8 && /\d/.test(pwd);
}
}
```
```html
<div class="login-form">
<!-- ... -->
<label>Password:</label>
<input ref="password"
:type="'password'"
placeholder="Enter your password..."
v-model.trim="userPwd"
@blur="checkPassword">
<!-- ... -->
</div>
```
这段代码会在用户离开密码输入区域后自动验证其有效性,并给出即时反馈。
#### 解决常见问题
有时可能会遇到一些棘手的问题,比如多次快速点击可能导致重复触发 `@blur` 或者与其他事件冲突。为了处理这种情况,可以在方法内部加入简单的防抖机制或者状态标记位防止不必要的重入。
另外值得注意的是,如果希望某些情况下不触发 `@blur` ,可以通过条件渲染的方式有条件地添加这个监听器。
最后提醒一点,对于移动设备来说,触摸屏幕可能不会像桌面端那样直观地引起 `@blur` 。因此开发响应式网站时需特别留意这一点[^4]。
阅读全文
相关推荐


















