如何在 vue 2 中正确使用 Veulidate 和 vuex
在下面的代码中,我在输入上使用两种方法来更新状态并应用 vuelidate 验证规则,现在验证规则未正确应用,$v.newEmloyeeName.$dirty
get 始终为 true。如何解决这个问题,以便状态得到更新并在输入上应用验证规则?我正在使用 vue 2
<input
type="text"
placeholder="Employee Name *"
@input="setNewEmployeeName; setName()"
:value="newEmployeeName">
<div v-if="$v.newEmloyeeName.$dirty">
<div class="text-danger" role="alert" v-if="!$v.newEmloyeeName.required">
<small>Employee Name is required</small>
</div>
</div>
...
<script>
import { required} from 'vuelidate/lib/validators'
import {mapMutations, mapState} from vuex;
export default{
validations: { newEmloyeeName: {required}},
computed: { ...mapState('addemployee',['newEmployeeName'])},
methods:{
...mapMutations('addemployee',['setNewEmployeeName']),
setName(){this.$v.newEmployeeName.$touch()}
}
</script>
In the following code, I use two methods on input to update both state and apply vuelidate validation rules, now validation rules doesn't applied properly, $v.newEmloyeeName.$dirty
get's always true. How to fix this so both state gets updated and validation rules applied on input? I'm using vue 2
<input
type="text"
placeholder="Employee Name *"
@input="setNewEmployeeName; setName()"
:value="newEmployeeName">
<div v-if="$v.newEmloyeeName.$dirty">
<div class="text-danger" role="alert" v-if="!$v.newEmloyeeName.required">
<small>Employee Name is required</small>
</div>
</div>
...
<script>
import { required} from 'vuelidate/lib/validators'
import {mapMutations, mapState} from vuex;
export default{
validations: { newEmloyeeName: {required}},
computed: { ...mapState('addemployee',['newEmployeeName'])},
methods:{
...mapMutations('addemployee',['setNewEmployeeName']),
setName(){this.$v.newEmployeeName.$touch()}
}
</script>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
v-on
指令接受表达式或回调函数作为事件处理程序。考虑到click
是一种方法,@click="click"
和@click="click($event)"
的行为方式相同,后者是明确的。setNewEmployeeName; setName()
是 JS 表达式,它的行为就像在模板之外进行计算一样;setNewEmployeeName
不会被调用,并且是一个无操作,但它应该提供字段值作为参数。最好不要在组件的
template
和script
部分之间分发 JS 代码。相反,它可以是:和
v-on
directive accepts expression or callback function as event handler. Considring thatclick
is a method,@click="click"
and@click="click($event)"
behave the same way, with the latter being explicit.setNewEmployeeName; setName()
is JS expression and it behaves like it would be evaluated outside the template;setNewEmployeeName
is not called and is a no-op, while it should be provided with field value as an argument.It's a good practice to not distribute JS code between
template
andscript
parts of a component. Instead, it can be:and