我们在移动端h5使用input
在v-model
双向数据绑定时候,ios的中文输入法下,输入英文却没有确认,直接失焦的情况下取不到该输入框的值,这是个坑。
解决方式
在input上多加个change
事件,用dom的方式赋值
代码如下:
<template>
<input
id="js-input"
type="text"
@change="inputChange"
placeholder="输入账号"
v-model="userName"
/>
</template>
<script>
export default {
data() {
userName:''
},
method(){
inputChange(){
this.userName = document.querySelector('#js-input').value
}
}
}
</script>
以上就可以解决该问题了。
不过,我在上面的基础上做了一层优化,用来移除空格。监听该input
的值,当用户使用中文输入法失焦是有空格的,所以需要用正则
的方式将空格移除。
export default {
// 以上代码加个监听事件
...
watch: {
userName:{
handler(newVal){
// newVal不为空 && 该值有空格
if(newVal && /\s/.test(newVal)){
newVal = newVal.toString().replace(/\s+/g, '');
this.$nextTick(() => {
this.userName = newVal
})
}
}
}
}
...
}