Reputation: 306
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>
Upvotes: 0
Views: 546
Reputation: 223259
v-on
directive accepts expression or callback function as event handler. Considring that click
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
and script
parts of a component. Instead, it can be:
@input="setName"
and
setName(event){
this.setNewEmployeeName(event.target.value);
this.$v.newEmployeeName.$touch()
}
Upvotes: 0