vue实现监听input变化
Vue 监听 input 变化的方法
在 Vue 中监听 input 变化可以通过多种方式实现,以下是几种常见的方法:
使用 v-model 和 watch
通过 v-model 绑定 input 的值,并使用 watch 监听数据变化:

<template>
<input v-model="inputValue" />
</template>
<script>
export default {
data() {
return {
inputValue: ''
}
},
watch: {
inputValue(newVal, oldVal) {
console.log('Input changed from', oldVal, 'to', newVal)
}
}
}
</script>
使用 v-on:input
直接监听 input 事件,适用于需要实时获取输入内容的情况:
<template>
<input :value="inputValue" @input="handleInput" />
</template>
<script>
export default {
data() {
return {
inputValue: ''
}
},
methods: {
handleInput(event) {
this.inputValue = event.target.value
console.log('Current input:', this.inputValue)
}
}
}
</script>
使用自定义指令
通过自定义指令实现更灵活的监听逻辑:

<template>
<input v-model="inputValue" v-input-listener />
</template>
<script>
export default {
data() {
return {
inputValue: ''
}
},
directives: {
'input-listener': {
inserted(el, binding, vnode) {
el.addEventListener('input', () => {
console.log('Input value:', vnode.context.inputValue)
})
}
}
}
}
</script>
使用计算属性
结合计算属性实现监听效果,适用于需要对输入值进行处理的场景:
<template>
<input v-model="inputValue" />
</template>
<script>
export default {
data() {
return {
inputValue: ''
}
},
computed: {
processedInput() {
console.log('Input processed:', this.inputValue)
return this.inputValue.trim()
}
}
}
</script>
使用 debounce 防抖
对于频繁触发的 input 事件,可以通过防抖优化性能:
<template>
<input v-model="inputValue" @input="debouncedInput" />
</template>
<script>
import _ from 'lodash'
export default {
data() {
return {
inputValue: ''
}
},
created() {
this.debouncedInput = _.debounce(this.handleInput, 500)
},
methods: {
handleInput() {
console.log('Debounced input:', this.inputValue)
}
}
}
</script>
每种方法适用于不同的场景,根据具体需求选择最合适的实现方式。






