背景:在vue定义了个子组件主要是一个登录框,在点击登录时需要对输入框的值进行判断
过程问题:当时用了网上推荐最多的ref和html的getElementById,但是发现输入框类型为password时就无法获取
解决办法:最终使用v-model双向绑定的方法解决
过程:按键触发函数如下run,先弹出提示框,内容为username的长度,然后判断password的长度是否为空(判断长度的原因是防止输入空格键),就发现if函数没反应,但alert能正常提示
template代码:
<input ref="username" type="text" >
<input ref=“userpassword” type="password" >
script中default的method函数:
methods:{
run:function(){
alert(this.$refs.username.length)
if(this.$refs.userpassword.length==0)
this.$emit('run',true)
else
this.$emit('run',false)
}
然后将alert中的内容换为this.$refs.userpassword.length发现a

在Vue的子组件中,当输入框类型为password时,使用ref和getElementById无法获取输入值。通过v-model双向绑定解决了这个问题。在模板中,将input的v-model分别绑定到username和userpassword变量,然后在方法中直接通过this.username和this.userpassword获取值,实现了对输入值的有效判断和操作。
最低0.47元/天 解锁文章
1257





