I'm making a basic form and I wanted to make the button visible only if all the fields were valid.
TEMPLATE:
<template>
<main>
<form @submit="send" method="POST">
<input id="name" type="text" placeholder="Nome" required minlength="3" maxlength="25" v-model="nome" @input="checkName" />
<div >{{errName}}</div>
<input id="lastName" type="text" placeholder="Cognome" required minlength="3" maxlength="25" v-model="cognome" @input="checkLastName" />
<div >{{errLastName}}</div>
<input id="email" type="email" placeholder="Email" required minlength="7" v-model="email" @input="checkEmail" />
<div >{{errEmail}}</div>
<input id="password" type="password" placeholder="Password" required minlength="3" maxlength="25" v-model="password" @input="checkPass" />
<div >{{errPass}}</div>
<button :style="buttonStyle" type="submit">INVIA</button>
</form>
</main>
</template>
SCRIPT (only the data()):
data() {
return {
nome: '',
cognome: '',
email: '',
password: '',
errName: '',
errLastName: '',
errEmail: '',
errPass: '',
validName: false,
validLastName: false,
validEmail: false,
validPass: false,
validForm: (this.validName && this.validLastName && this.validEmail && this.validPass),
buttonStyle: (this.validForm) ? 'display: block' : 'display: none'
}
}
I was expecting this.validForm
to become true once all the others were true, but instead, it stays false no matter what I do.
Some things I tried:
- Setting all
valid*
to true // DIDN'T WORK
validName: true,
validLastName: true,
validEmail: true,
validPass: true,
- Setting
validForm
to true // DIDN'T WORK
validForm: true,
buttonStyle: (this.validForm) ? 'display: block' : 'display: none'
- Swapping the returns on
buttonStyle
// SHOWED THE BUTTON
buttonStyle: (this.validForm) ? 'display: none' : 'display: block'
As I said, the last try actually showed the button...but it's obviously not what I wanted.
I'm new to Vue so I'm still learning all the functionalities.
CodePudding user response:
Summary:
Without seeing any of your logic I couldn't tell you how to fix the boolean but instead of using the buttonStyle property you should use v-if.
v-if will make your component render ONLY when the boolean inside of it is true.
Example:
var isTrue = true;
<button v-if='1 < 2'></button> // Will Render
<button v-if=isTrue></button> // Will Render
<button v-if='1 1 == 7'></button> // Will NOT Render
Documentation:
Here's the documentation if you'd like to look into it more: