[Vuejs]-Use same elements in v-if and v-else

0👍

One way is to use the v-if in a <template> to handle the conditional part, leaving the common part out:

<transition v-bind:name="TabEffect">
    <div v-for="(logTab, i) of [true, false]" v-if="logTab" :key="i+1" :class="LoginTab ? 'login' : 'register'">
        <template v-if="LoginTab">
            <div>
                <label class="inputText" for="email">Email Address</label>
                <input type="text" name="email" id="email" placeholder="Test@TestMail.com"/>
            </div>
            <div>
                <label class="inputText" for="password">Password</label>
                <input type="password" name="password" id="password" placeholder="Your Password"/>
            </div>
        </template>
        <template v-else>
            <div>
                <label class="inputText" for="email">Email Address</label>
                <input type="text" name="email" id="email" placeholder="Test@TestMail.com"/>
            </div>
            <div>
                <label class="inputText" for="password">Password</label>
                <input type="password" name="password" id="password" placeholder="Your Password"/>
            </div>
            <div>
                <label class="inputText" for="Cpassword">Repeat Password</label>
                <input type="password" name="Cpassword" id="Cpassword" placeholder="Repeat Password"/>
            </div>
        </template>

        <button>{{ LoginTab ? 'Login' : 'Register' }}</button>
        <span class="or">or</span>
        <a href="#!" class="steamLogin">
            <i class="fab fa-steam"></i>
            <span>Login with Steam</span>
        </a>
    </div>
</transition>

Lastly, as the main div‘s class also depends on the LoginTab variable, we have to put a :class to handle it.

On a side note, only the Repeat password of your code seems to be the varying part. Still, I left the email/password in the conditional to be more faithful to your original question. (And because to change this would be very easy.)

Leave a comment