[英]Input field live validation using vuejs
I got an input field, which I want to be live validated. 我有一个输入字段,我想对其进行实时验证。 As its only one single field, I would like to avoid using a whole library for vue form validations. 作为唯一的一个字段,我想避免使用整个库进行vue表单验证。
There are three things I would like to accomplish: 我要完成三件事:
ac
is valid, while a
is not. 例如, ac
有效,而a
无效。 Although abc
is valid. 虽然abc
有效。 valid
or invalid
, depending on the validation 输入字段包装在#wrapper中,该包装应使用valid
或invalid
,具体取决于验证 .alert
should show. 如果用户尝试发送无效的字符串(通过单击按钮或按Enter键), .alert
显示.alert
。 I have tried to write a vue script: 我试图编写一个Vue脚本:
computed: {
inputClass: function () {
var inputField=document.getElementById("inputField").value;
if (inputField==null || inputField=="") {
return 'invalid';
} else {
return 'valid';
}
}
}
Sadly, this script always returns 'valid', even when the input field is empty. 遗憾的是,即使输入字段为空,该脚本也始终返回“ valid”。
As I am using vue.js for some other reasons, it seems a good idea to implement this inside my vue app. 由于其他原因,我正在使用vue.js,因此在我的vue应用程序中实现此功能似乎是一个好主意。 But I could although use jQuery. 但是我虽然可以使用jQuery。 I have tried to solve the third need of my list with the following script: 我尝试使用以下脚本解决列表的第三个需求:
$('button').on('click', function(){
if( $(this).val().length === 0 ) {
$('.alert').fadeIn();
} else {
$('.alert').hide();
}
});
To make it easier to understand I have created a JS Bin with the HTML markup and code. 为了更容易理解, 我创建了带有HTML标记和代码的JS Bin 。
You should go through the vuejs documentation, it seems you don't really have a grasp of what the framework is about. 您应该仔细阅读vuejs文档,看来您对框架的含义并不真正了解。
A computed variable will only be recalculated when the data of the instance will be updated. 仅当实例数据更新时,才会重新计算计算出的变量。 Here, there's no way to react to anything therefore the inputClass will never get computed again. 在这里,无法对任何事情做出反应,因此inputClass将永远不会被再次计算。
I've modified your example to bind your input to the instance. 我已经修改了您的示例,以将您的输入绑定到实例。
I declared it in the data propriety and in the html as a v-model. 我在数据专有性和html中将其声明为v模型。
var app = new Vue({
el: '#app',
data: {
"input": "",
},
computed: {
inputClass: function () {
var inputField=document.getElementById("inputField").value;
if (this.input === "") {
return 'invalid';
} else {
return 'valid';
}
}
}
});
<input v-model="input" type="text" placeholder="Type your full name..." id="inputField">
Now it's working 现在可以了
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.