uniapp @input如何使用
2 回复
在uniapp中,使用@input绑定输入事件,例如:
<input @input="handleInput" />
在methods中定义方法:
handleInput(e) {
console.log(e.detail.value)
}
这样就能实时获取输入框内容。
在uni-app中使用@input事件,主要用于监听输入框内容的变化。以下是基本用法和示例:
基本语法
<template>
<input
type="text"
@input="handleInput"
:value="inputValue"
placeholder="请输入内容"
/>
</template>
<script>
export default {
data() {
return {
inputValue: ''
}
},
methods: {
handleInput(event) {
// 获取输入的值
this.inputValue = event.detail.value
console.log('输入内容:', this.inputValue)
}
}
}
</script>
常用场景示例
1. 实时搜索
<template>
<input
type="text"
@input="onSearchInput"
placeholder="搜索..."
/>
</template>
<script>
export default {
methods: {
onSearchInput(event) {
const keyword = event.detail.value
// 防抖处理
clearTimeout(this.timer)
this.timer = setTimeout(() => {
this.search(keyword)
}, 500)
},
search(keyword) {
// 执行搜索逻辑
console.log('搜索关键词:', keyword)
}
}
}
</script>
2. 表单验证
<template>
<input
type="text"
@input="validateEmail"
placeholder="请输入邮箱"
/>
<text v-if="errorMsg" style="color: red;">{{ errorMsg }}</text>
</template>
<script>
export default {
data() {
return {
errorMsg: ''
}
},
methods: {
validateEmail(event) {
const email = event.detail.value
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
if (!emailRegex.test(email)) {
this.errorMsg = '邮箱格式不正确'
} else {
this.errorMsg = ''
}
}
}
}
</script>
注意事项
@input在输入内容每次变化时触发- 通过
event.detail.value获取输入值 - 在H5和小程序平台表现一致
- 如需限制输入长度,可配合
maxlength属性使用
这样可以实现输入框内容的实时监听和处理。

