我有一个输入,我想在提交之前检查哪些内容。根据状态(输入正确或错误),我设置了一个类来反馈给用户:
new Vue({
el: "#app",
data: {
input: ""
},
methods: {
getClass() {
if (this.input == "") {
return "ko";
} else {
return "ok";
}
}
}
});
.ok {
border-width: 3px;
border-color: green;
}
.ko {
border-width: 5px;
border-color: red;
}
.initial {
border-width: 1px;
border-color: gray;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.11/vue.js"></script>
<div id="app">
<input v-bind:class="getClass(input)" v-model="input">
</div>
它工作正常,除了我想在对该给定字段(上面示例中的 <input>
)进行任何操作之前拥有一个中性样式并拥有类 initial
适用于这种情况。
这在 Vue 中很容易做到吗?我可以想象听到每个 clicked
事件并根据它设置类(第一个 initial
然后根据内容设置正确的类)但这相当麻烦。
换句话说,在用户第一次与该元素交互之前,不会向用户显示任何指示。
有没有一种自然的方法可以实现这一目标?
最佳答案
只需在数据属性中添加一个额外的属性touched
,这是一个 bool 值,用于保存输入是否最初被触摸
new Vue({
el: "#app",
data: {
input: "",
touched: false
},
methods: {
getClass() {
if(!this.touched){
return 'initial';
}else{
if(this.input == "") {
return "ko";
} else {
return "ok";
}
}
}
}
});
在输入更改时将 touched
的值设置为 true
<input v-bind:class="getClass(input)" @change="this.touched = true" v-model="input">
关于javascript - 在 Vue 中有通用的方式来表示 "not interacted with yet"吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47844677/