Search code examples
htmlvue.jsvuejs2conditional-rendering

why is conditional rendering not working for form input in vuejs


I have a form with select options :

        <div>
            <select>
                <option v-model="department" :value="n" v-for="n in ['Please select', 'Medicine', 'Dental']">{{n}}</option>
            </select>
        </div>
        <div class="alignBtn">
            <label><span>&nbsp;</span><input type="submit" v-on:click.prevent="generateSlip()" value="Submit" />
            </label>
        </div>

and based on the selection in the above I want to display header content:

               <div v-if="{department} === 'Medicine'">
                    <h1>Option A</h1>
                </div>
                <div v-else>
                    <h1>Option B</h1>
                </div>

but every time Option B is getting outputted .


Solution

  • I think that the v-model directive should be in the select element. You probably meant to do this ..

    <div>
        <select v-model="department">
            <option :value="n" v-for="n in ['Please select', 'Medicine', 'Dental']">{{n}}</option>
        </select>
    </div>
    <div class="alignBtn">
        <label><span>&nbsp;</span><input type="submit" v-on:click.prevent="generateSlip()" value="Submit" />
        </label>
    </div>
    

    You also don't need destructuring in this case. So you can use department in your equality comparison directly ..

    <div v-if="department === 'Medicine'">
        <h1>Option A</h1>
    </div>
    <div v-else>
        <h1>Option B</h1>
    </div>