Update b-field message after button click - vue.js

I'm very new in Vue, and I'm trying to do a simple thing of displaying the result in a b-field after clicking a button.
Below is my Login.vue code
<template>
<section id="login">
<h1>Login</h1>
<b-field label=""
type="is-warning"
message="Please enter a valid email">
<b-input type="email" name="email" v-model="input.email" placeholder="E-mail"></b-input>
</b-field>
<b-field label=""
type="is-warning"
message="Please enter your password">
<b-input type="password" name="password" v-model="input.password" placeholder="Password"></b-input>
</b-field>
<b-field message="hohoho"
type="is-danger"
name="result"
>
<button type="button" v-on:click="login()" class="button">Login</button>
</b-field>
</section>
</template>
<script>
export default {
name: 'Login',
data () {
return {
input: {
email: "",
password: ""
}
}
},
methods: {
login () {
if(this.input.email != "" && this.input.password != "") {
if(this.input.email == this.$parent.mockAccount.email && this.input.password == this.$parent.mockAccount.password) {
this.$emit("authenticated", true)
this.$router.replace({ name: "secure" })
} else {
this.result = "The email and / or password is incorrect"
console.log("The email and / or password is incorrect")
}
} else {
this.result = "An email and password must be present"
console.log("An email and password must be present")
}
}
}
}
</script>
I have problem updating the content of the b-field with name result... the this.result doesn't update the content of the b-field.

I guess you want to update the message attribute of this element?
<b-field message="hohoho"
type="is-danger"
name="result">
<button type="button" v-on:click="login()" class="button">Login</button>
</b-field>
If I am correct you just need to bind the result prop to the message attribute like this:
<b-field :message="result"
type="is-danger"
name="result">
<button type="button" v-on:click="login()" class="button">Login</button>
</b-field>
Notice the :message="result", it's a shortcut for v-bind:message="result".
Also, very important, you need to define the result prop in data
data () {
return {
input: {
email: "",
password: ""
},
result: ""
}
},
More info here

Related

vee-validate in steps form

I have a problem I'm trying to learn vee-validate
to a form that has steps but the problem is like as far
as the first drop I validate correctly a field from the second step is no longer works properly or someone could help this is all component and methods i think this is scope problem but i don't now?
<template>
<div>
<div v-if="step === 1">
<input
class="form-control loginForm__input"
type="text"
:class="{'input': true, 'is-invalid': errors.has('email') }"
name="email"
v-validate="'required|email'"
placeholder="Email adress"
v-model="registration.email"
/>
</div>
<div v-if="step === 2">
<input
class="form-control loginForm__input"
:class="{'input': true, 'is-invalid': errors.has('nameFirst') }"
v-validate="'required'"
name="nameFirst"
type="text"
placeholder="name"
v-model="registration.nameFirst"
/>
<div class="LoginButton">
<button
type="button"
class="btn button__blue"
#click="nextStep();progressbarNext();"
>Continue</button>
</div>
</div>
</template>
<script>
export default {
name: "Register",
components: {
},
data: function() {
return {
step: 1,
registration: {
email: null,
nameFirst: null,
}
};
},
computed: {},
methods: {
goBack() {
if (this.step === 1) {
this.$router.push("/");
return;
}
this.step--;
},
nextStep() {
this.$validator.validateAll().then(result => {
console.log(result);
if (result) {
if (this.step === 3) {
this.showModal = true;
(this.stepBannerThree = true), (this.step = 3);
return;
}
this.step++;
if (this.step == 2) {
return (this.stepBannerOne = true);
}
if (this.step == 3) {
return (this.stepBannerTwo = true);
}
return;
}
});
},
}
};
</script> ```

#submit.prevent not working on vue md-input

when I click 'login button' even I don't fill data in md-input it still running,
I test my onSubmit() method by login with my user and it works!
I don't think I do thing wrong in the method so I guess that my form is incorrect.
here is my code :
my form
<form #submit.prevent="onSubmit">
<login-card header-color="green">
<h4 slot="title" class="title">CCRP Sign On</h4>
<p slot="description" class="description">IT solution by เจ้เก๋ IT-PM</p>
<md-field class="md-form-group" slot="inputs">
<md-icon>account_box</md-icon>
<label>ID...</label>
<md-input v-model.trim="userId" type="text"></md-input>
</md-field>
<md-field class="md-form-group" slot="inputs">
<md-icon>lock_outline</md-icon>
<label>Password...</label>
<md-input v-model.trim="password" type="password"></md-input>
</md-field>
<md-field class="md-form-group">
<md-icon>announcement</md-icon>
<label>Password...</label>
</md-field>
<md-button slot="footer" class="md-simple md-success md-lg" type="submit">Login</md-button>
</login-card>
</form>
in scrpit methods
async onSubmit() {
const authData = {
userId: this.userId,
password: this.password
};
await this.login(authData).then(() => {
if (this.isAuthenticated) {
this.$router.push("dashboard");
} else {
console.log("err");
}
});
},
can you help me solve this?
Your understanding of "prevent" key is quite incorrect.
All it does is not reload the form after submit action. However the submit action will be called irrespective of whether the prevent is used or not.
It is just preventing the default functionality of form getting reloaded after each submit.
On the other hand what you need to do is validate your form before actually submitting it.
Example :
//- Requires "vuelidate" - npm install vuelidate
<script>
import { validationMixin } from "vuelidate";
import { required, email } from "vuelidate/lib/validators";
export default {
name: "FormValidation",
mixins: [validationMixin],
data: () => ({
form: {
email: null,
password: null
},
userSaved: false,
sending: false,
lastUser: null
}),
validations: {
form: {
email: {
required,
email
},
password: {
required
}
}
},
methods: {
getValidationClass(fieldName) {
const field = this.$v.form[fieldName];
if (field) {
return {
"md-invalid": field.$invalid && field.$dirty
};
}
},
clearForm() {
this.$v.$reset();
this.form.email = null;
this.form.password = null;
},
saveUser() {
this.sending = true;
// Instead of this timeout, here you can call your API
window.setTimeout(() => {
this.lastUser = `${this.form.email}`;
this.userSaved = true;
this.sending = false;
this.clearForm();
}, 1500);
},
validateUser() {
this.$v.$touch();
if (!this.$v.$invalid) {
this.saveUser();
}
}
}
};
</script>
<style lang="scss" scoped>
.md-progress-bar {
position: absolute;
top: 0;
right: 0;
left: 0;
}
</style>
<template>
<div>
<!-- Calling validateUser insted of submit action -->
<form novalidate class="md-layout" #submit.prevent="validateUser">
<md-card class="md-layout-item md-size-50 md-small-size-100">
<!-- Title of the form -->
<md-card-header>
<div class="md-title">Login</div>
</md-card-header>
<!-- Inputs for the form -->
<md-card-content>
<md-field :class="getValidationClass('email')">
<label for="email">Email</label>
<md-input
type="email"
name="email"
id="email"
autocomplete="email"
v-model="form.email"
:disabled="sending"
/>
<span class="md-error" v-if="!$v.form.email.required">The email is required</span>
<span class="md-error" v-else-if="!$v.form.email.email">Invalid email</span>
</md-field>
<md-field :class="getValidationClass('password')">
<label for="password">Password</label>
<md-input
type="password"
name="password"
id="password"
autocomplete="password"
v-model="form.password"
:disabled="sending"
/>
<!-- to show errors in case validation fails -->
<span class="md-error" v-if="!$v.form.password.required">The email is required</span>
<span class="md-error" v-else-if="!$v.form.email.email">Invalid email</span>
</md-field>
</md-card-content>
<md-progress-bar md-mode="indeterminate" v-if="sending"/>
<md-card-actions>
<md-button type="submit" class="md-primary" :disabled="sending">Create user</md-button>
</md-card-actions>
</md-card>
<md-snackbar :md-active.sync="userSaved">The user {{ lastUser }} was saved with success!</md-snackbar>
</form>
</div>
</template>

How to prevent default, then submit default with VueJS

I am submitting a form using VueJS and i need to submit two actions on the final submit, one after the other.
Either one works when running just one.
What i am trying to do, is signup a user for firebase, wait, then submit the form with the same email/password as normal and signup that user with another sign in system.
The delimiters have been changed, so just over look that.
How to do this with Jquery
<form #submit="checkForm" #submit.prevent="register" action="#" method="post" novalidate="true" ref="form">
<h1 class="text-center">{{ 'customer.register.title' | t }}</h1>
<h1 v-if="authUser">
Is authed in
</h1>
<h1 v-else>
Not auth
</h1>
<div class="form-group">
<ul>
<li v-for="error in errors">
${ error }
</li>
</ul>
</div>
<p>
<label for="CustomerFirstName">${ firstName }</label>
<input id="name" v-model="name" type="name" name="customer[first_name]" autocomplete="name"
autocorrect="off" autocapitalize="off">
</p>
<p>
<label for="CustomerEmail">${ loginEmailName }</label>
<input id="email" v-model="email" type="email" name="customer[email]" autocomplete="email"
autocorrect="off" autocapitalize="off">
</p>
<p>
<label for="CustomerPassword">${ loginPasswordName }</label>
<input id="password" v-model="password" type="password" name="customer[password]">
</p>
<p>
<button type="submit" value="Create" class="btn btn-primary">Submit</button>
</p>
</form>
Then the JS that works on either one but not together.
const appTwo = new Vue({
delimiters: ["${", "}"],
el: "#create_customer_vue",
data: {
errors: ["1", "2", "3"],
email: '',
password: '',
name: null,
firstName: "First name",
loginEmailName: emailTitle,
loginPasswordName: passwordTitle,
title: registerTitle,
authUser: null
},
methods: {
register: function() {
firebase.auth().createUserWithEmailAndPassword(this.email, this.password)
},
submitForm: function(){
this.$refs.form.submit()
},
created() {
firebase.auth().onAuthStateChanged(user => { this.authUser = user })
},
checkForm: function(e) {
if (this.email && this.password) {
return true;
}
this.errors = [];
if (!this.email) {
this.errors.push("Valid email required");
}
if (!this.password) {
this.errors.push("Valid password required");
}
e.preventDefault();
}
}
});
Just call the one submit handler then submit the form normally after the Firebase operation completes.
For example
<form #submit.prevent="register" ... >
methods: {
checkForm () {
if (this.email && this.password) {
return true;
}
this.errors = [];
if (!this.email) {
this.errors.push("Valid email required");
}
if (!this.password) {
this.errors.push("Valid password required");
}
return false
},
async register ($event) {
if (this.checkForm()) {
await firebase.auth().createUserWithEmailAndPassword(this.email, this.password)
$event.target.submit() // or use this.$refs.form.submit() if you prefer
}
}
}

Simple If return in VUE.JS method

Template won't show v-if when method return true.
I can log the username password and the failed attempt in the else section of my login method. If I try to log the loginFailed var I get loginFailed is not defined.
<template>
<div class="container-big">
<div class="container-header">
<h1>Our Login</h1>
</div>
<p v-if="loginFailed">
Login Failed
</p>
<div id="loginContainer" class="container-login">
<P>{{msg}}</p>
<input id="login" type="text" placeholder="username" v-model="username" spellcheck="false" >
<input id="key" type="password" placeholder="password" v-model="password" spellcheck="false" >
</div>
<div class="container-signin">
<button class="signin" id="go" #click="login()"></button>
</div>
</div>
</template>
<script>
export default {
name: 'Login',
data () {
return {
msg: 'This is your login',
password: '',
username: '',
loginFailed: false
}
},
methods: {
login () {
console.log(this.username);
console.log(this.password);
if (this.username !== '' && this.password === 'pass') {
this.$router.push( { name: 'dashboard', path: '/dashboard' }) }
else {
console.log('failed attempt')
this.loginFailed === true;
return this.loginFailed
}
}
}
}
</script>
What I want to do is if login failed show
<p v-if="loginFailed">
Login Failed
</p>
In the login() method, you're performing a comparison when you should actually assign a value to the loginFailed property:
this.loginFailed === true;
Change that line so that it actually assigns true to this.loginFailed:
this.loginFailed = true;
side note: You most likely don't need to return anything from login() since it's simply dealing with instance properties, you might want to remove this line:
return this.loginFailed

Veevalidate always return true Vuejs

I´m using webpack and instance VeeValidate using this way:
import VeeValidate from 'vee-validate';
Vue.use(VeeValidate, {
// This is the default
inject: true,
// Important to name this something other than 'fields'
fieldsBagName: 'veeFields'
});
I have a vuejs component created for the user to subscribe to the email. The problem is that this form always gives true when I use $validator.validateAll()
Have I not understood well the functioning of Vee-validate?
This is the code of my component newsletter.vue.js
Vue.component('newsletter', {
template : '<div>\
<b-form inline>\
<b-input v-validate required id="email" name="email" class="mb-2 mr-sm-2 mb-sm-0" placeholder="Deja tu email" type="email" :state="validate_input" />\
\
<b-button variant="primary-degree" #click="validateBeforeSubmit">Enviar</b-button>\
</b-form>\
</div>',
props : ['route_post'],
inject: ['$validator'],
data() {
return {
email: '',
}
},
computed: {
validate_input: function() {
return this.errors.has("email")
}
},
methods: {
onSubmit() {
// Form submit logic
},
validateBeforeSubmit() {
this.$validator.validateAll().then((result) => {
console.log(result);
if (result) {
// eslint-disable-next-line
alert('Form Submitted!');
return;
}
alert('Correct them errors!');
});
}
}
});
In order to add a validation of vee-validate you need to add it as value to v-validate option and not directly within the tag.
For more info check required example on docs
Update the below line in your code.
<b-input v-validate="'required'" id="email" name="email" class="mb-2 mr-sm-2 mb-sm-0" placeholder="Deja tu email" type="email" :state="validate_input" />
If you also want to display error you can add below line as =>
<span class="error" v-if="errors.has('email')">{{ errors.first('email') }}</span>