uniapp @input如何使用

在uniapp中,如何使用@input事件?我在组件中绑定了@input,但触发时获取不到输入框的值,请问正确的写法是什么?需要配合v-model一起使用吗?最好能提供一个示例代码说明。

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属性使用

这样可以实现输入框内容的实时监听和处理。

回到顶部