uniapp @input 事件后如何实现文本框置空并保持光标定位
2 回复
在@input事件中,使用$refs获取input元素,调用focus()方法保持光标定位,同时清空v-model绑定的值。
示例:
handleInput() {
this.inputValue = ''; // 清空文本框
this.$nextTick(() => {
this.$refs.input.focus(); // 重新聚焦
});
}
在 UniApp 中,可以通过以下步骤实现 @input 事件触发后清空文本框并保持光标定位:
实现方法
- 使用
v-model绑定数据:确保文本框与数据双向绑定。 - 在
@input事件中处理:通过$nextTick确保 DOM 更新后操作光标。 - 操作输入框元素:通过
ref获取输入框实例,调用focus方法重新聚焦。
示例代码
<template>
<view>
<input
ref="inputRef"
v-model="inputValue"
@input="handleInput"
placeholder="请输入内容"
/>
</view>
</template>
<script>
export default {
data() {
return {
inputValue: ''
};
},
methods: {
handleInput() {
// 清空文本框
this.inputValue = '';
// 使用 $nextTick 确保 DOM 更新后操作
this.$nextTick(() => {
// 通过 ref 获取输入框并聚焦
this.$refs.inputRef.focus();
});
}
}
};
</script>
注意事项
$nextTick的作用:确保清空操作引起的 DOM 更新完成后再聚焦,避免光标闪烁或定位失败。- 兼容性:在 UniApp 的 H5 和部分小程序平台(如微信小程序)中测试通过。如果遇到平台差异,可能需要根据具体平台调整。
- 性能:频繁触发
@input时,注意避免过度操作 DOM 影响性能。
通过以上方法,即可在输入事件后清空内容并保持光标定位。

