Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue prop validation getting executed every time there is input on another component

I have a Vue component as follows:

<template>
<div>
    <div class="sel-square"
        @click="selectGender('Male')"
        :class="{ active : value === 'Male'}">
    <div class="sel-square__img">
        <img src="~Img/lp_v1/fam-male.png"
            alt="male" />
    </div>
    <div class="sel-square__caption">
        Male
    </div>
    </div>

    <div class="sel-square"
    @click="selectGender('Female')"
    :class="{ active : value === 'Female'}">
    <div class="sel-square__img">
        <img src="~Img/lp_v1/fam-female.png"
            alt="female" />
    </div>
    <div class="sel-square__caption">
        Female
    </div>
    </div>
</div>
</template>

<script>
export default {
props : { 
    value: {
    type: String,
    required: true,
    validator: (value) => {
        console.log("Validating", value)
        return ['Male', 'Female'].includes(value)
    }   
    }   
},  
methods :{
    selectGender(gender) {
    console.log("Emiting input", gender)
    this.$emit('input', gender)
    }   
}   
}   
</script>

I am using this in my main App as:

<GenderSelector v-model="gender"></GenderSelector>

The issue I am facing is that the 'validator' runs 3-4 times the very first time I refresh the page and after that it keep executing on every keypress on another input element I have on the same page. Just to be clear, the console output keeps showing "Validating Male" again and again and the "Emiting input" only shows on console when I click.

Is Vue validating props again and again on every input event? Its unlikely, so what am I doing wrong here?

JSFiddle: https://jsfiddle.net/eywraw8t/5090/

like image 448
rane Avatar asked Mar 31 '18 17:03

rane


1 Answers

That's perfectly normal, you are not doing anything wrong. Prop validation is triggered whenever the component re-renders like when a prop changes.

When using v-model on a component, whenever you emit input event, the component re-renders because it effectively updates the value prop. The component itself doesn't update the value prop but rather it's parent. because v-model is more or less a shorthand of :value="value" @input="value = $event". So the component re-renders and the validation is triggered.

You shouldn't worry about it, I would argue that you don't need the validator as your component is likely to always emit valid values.

like image 121
logaretm Avatar answered Oct 22 '22 13:10

logaretm