So for form actions, I made a class to make things cleaner, but there's a problem. Whenever any errors/success messages are set in the class, Svelte does not automatically rerender the changes.
Frontend:
<script>
import Form from '#/periphs/form'
let changePasswordForm = new Form()
changePasswordForm.form.values = {
newPassword: null,
currentPassword: null
}
changePasswordForm.params.endpoint = route('api.user.settings.security.change-password')
const changePassword = () => {
changePasswordForm.execute()
}
</script>
<div class="block">
<div class="is-size-6 has-text-weight-light">Change Password</div>
<div class="field help has-text-grey-light">
1. Use special characters. (!##$%^&*)
<br>2. Do not reuse passwords.
<br>3. Do not use passwords that can be guessed. (Birthdays, names, numbers, etc).
</div>
<fieldset disabled={ changePasswordForm.form.processing }>
<div class="field">
<div class="control">
<label for="" class="label is-small">New Password</label>
<input bind:value={ changePasswordForm.form.values.newPassword } class:is-danger={ changePasswordForm.form.errors.newPassword } type="password" class="input is-small" placeholder="New Password">
</div>
{#if changePasswordForm.form.errors.newPassword}
<div class="help is-danger">{ changePasswordForm.form.errors.newPassword }</div>
{/if}
</div>
<div class="field">
<div class="control">
<label for="" class="label is-small">Current Password</label>
<input bind:value={ changePasswordForm.form.values.currentPassword } class:is-danger={ changePasswordForm.form.errors.currentPassword } type="password" class="input is-small" placeholder="Current Password Password">
</div>
{#if changePasswordForm.form.errors.currentPassword}
<div class="help is-danger">{ changePasswordForm.form.errors.currentPassword }</div>
{/if}
</div>
<div class="field">
<button on:click={ () => changePassword() } class="button is-primary is-small">Change Password</button>
{#if changePasswordForm.form.success.message}
<div class="help is-success">{ changePasswordForm.success.message }</div>
{/if}
{#if changePasswordForm.form.errors._flood}
<div class="help is-danger">{ changePasswordForm.errors._flood }</div>
{/if}
</div>
</fieldset>
</div>
Form.js:
'use strict'
import axios from "axios"
export default class Form {
constructor() {
this.form = {
processing: false,
success: {},
errors: {},
values: {}
}
this.params = {
method: 'POST',
endpoint: null,
}
}
getErrors() {
return this.form.errors
}
execute() {
/*
Before form submission, reset all errors/successes
*/
this.form.processing = true
this.form.success = {}
this.form.errors = {}
if (this.params.method == 'POST') {
axios.post(this.params.endpoint).then(r => {
/*
Handle success
*/
this.form.errors = {}
this.form.success = r.data
}).catch(e => {
/*
422
Form errors (Validation)
*/
if (e.response.status == 422) {
this.form.errors = e.response.data.errors
}
/*
429
Request timeout (Flood)
*/
if (e.response.status == 429) {
this.form.errors = { ...this.form.errors, ...{ '_flood': e.response.data.message } }
}
console.log(this.form.errors) // SHOWS ERRORS AS ITS SUPPOSED TO, BUT THIS IS NOT REPRODUCED ON THE FRONTEND
}).finally(() => {
this.form.processing = false
})
}
}
}
Whenever there is an error/success, it should show those changes on my front end, but that is not the case. Any one got any idea on how to fix this?
Reactivity only works for code within components, outside you need to use stores or events to signal changes.
Related
I'm creating login validation in Vue.js but the error message is not displaying and it gives me the error:
Property or method "error" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property.
Any help?
Template:
<template>
<div class="container" width="900">
<div class="row justify-content-center" style="margin-top: 10px;">
<div class="col-5">
<div v-if="error" class="alert alert-danger" role="alert">
{{error}}
</div>
<div class="card" >
<div class="card-text">
<div class="form-group" #keyup.enter="logItIn">
<input class="form-control"
v-model="login.email"
label="Email"
placeholder="Email Address"
required
> <br>
<input class="form-control"
v-model="login.password"
label="Password"
type="password"
placeholder="Password"
required>
</div>
</div>
<button type="button" class="btn btn-secondary" #click='logItIn'>Login</button>
</div>
</div>
</div>
</div>
</template>
Script:
import axios from 'axios'
export default {
data() {
return {
login: {
email:"",
password:"",
error: ""
}
}
},
methods: {
async logItIn() {
try {
axios.post('https://odevin-api.herokuapp.com/login',this.login)
.then(response => {
console.log(response)
let newToken=response.data.response.token;
window.token=newToken;
let user=response.data.response.user; //response
localStorage.setItem('token',newToken);
localStorage.setItem('user',JSON.stringify(user));
window.axios.defaults.params={api_token:newToken}
// Event.$emit('login',user);
this.$router.push('/');
});
} catch(e) {
this.error = 'invalid user name or password';
}
}
}
}
you referenced {{ error }} in your template but in your data object, error is a property of login object. so vue can't find it properly.
either change the usage in your template to {{ login.error }} or define it in your data object like this:
data() {
return {
error: '',
login: {
email: '',
password: '',
},
}
}
Good morning all,
Here I am starting in vue.js and I get stuck on a point that does not seem complicated.
Indeed, I try to pass my list of localities, in my adduser component. So that when creating the user he has to select localities.
But impossible to pass the list to him yet I know that it is necessary to use the props but I can not.
Can you help me ?
Thank you
Component Add user :
<template>
<div class="submitform">
<div v-if="!submitted">
<div class="form-group">
<label for="nom">Nom</label>
<input type="text" class="form-control" id="nom" required v-model="utilisateur.nom" name="nom">
</div>
<div class="form-group">
<label for="prenom">Prenom</label>
<input type="text" class="form-control" id="prenom" required v-model="utilisateur.prenom" name="prenom">
</div>
<div class="form-group">
<label for="profession">Profession</label>
<input type="text" class="form-control" id="profession" required v-model="utilisateur.profession" name="profession">
</div>
<div class="form-group">
<label for="adresse">Adresse</label>
<input type="text" class="form-control" id="adresse" required v-model="utilisateur.adresse" name="adresse">
</div>
<div class="form-group">
<label for="email">Email</label>
<input type="text" class="form-control" id="email" required v-model="utilisateur.email" name="email">
</div>
<div class="form-group">
<label for="login">Login</label>
<input type="text" class="form-control" id="login" required v-model="utilisateur.login" name="login">
</div>
<div class="form-group">
<label for="mobile">Mobile</label>
<input type="text" class="form-control" id="mobile" required v-model="utilisateur.mobile" name="mobile">
</div>
<div class="form-group">
<label for="password">password</label>
<input type="text" class="form-control" id="password" required v-model="utilisateur.password" name="password">
</div>
<!--<div>
<ul>
<li v-for="(localite, index) in localites" :key="index">
{{localite.ville}}
</li>
</ul>
</div>-->
<!--<div>
<select>
<option v-for="(localite, index) in localites" :key="index">
{{localite.ville}}
</option>
</select>
</div>-->
<button v-on:click="saveUtilisateur" class="btn btn-success">Submit</button>
</div>
<div v-else>
<h4>You submitted successfully!</h4>
<button class="btn btn-success" v-on:click="newUtilisateur">Add</button>
</div>
</div>
</template>
<script>
import http from "../http-common";
import Localite from "../components/LocalitesList.vue"
export default {
name: "add-utilisateur",
data()
{
return {
utilisateur: {
id: 0,
nom:"",
prenom:"",
profession:"",
adresse:"",
email:"",
login:"",
mobile:"",
password:"",
actif: 0,
localite: 0
},
Localite: [],
submitted: false
};
},
components:
{
'localite': Localite
},
methods:
{
/* eslint-disable no-console */
saveUtilisateur() {
var data = {
nom: this.utilisateur.nom,
prenom: this.utilisateur.prenom,
profession: this.utilisateur.profession,
adresse: this.utilisateur.adresse,
email: this.utilisateur.email,
login: this.utilisateur.login,
mobile: this.utilisateur.mobile,
password: this.utilisateur.password,
localite: this.utilisateur.localite
};
http
.post("/utilisateur", data)
.then(response => {
this.utilisateur.id = response.data.id;
console.log(response.data);
})
.catch(e => {
console.log(e);
});
this.submitted = true;
},
/* retrieveLocalites() {
http
.get("/localites")
.then(response => {
this.localites = response.data; // JSON are parsed automatically.
console.log(response.data);
})
.catch(e => {
console.log(e);
});
},
refreshList() {
this.retrieveLocalites();
}
/* eslint-enable no-console */
},
/*mounted() {
this.retrieveLocalites();
}*/
/* eslint-enable no-console */
};
</script>
<style>
.submitform {
max-width: 300px;
margin: auto;
}
</style>
Component Localite:
<template>
<div v-if="this.localite">
<h4>Localite</h4>
<div>
<label>CP: </label> {{this.localite.cp}}
</div>
<div>
<label>Ville: </label> {{this.localite.ville}}
</div>
<span class="button is-small btn-danger" v-on:click="deleteLocalite()">Delete</span>
</div>
<div v-else>
<br/>
<p>Please click on a Localite...</p>
</div>
</template>
<script>
import http from "../http-common";
export default
{
name: "localite",
props: ["localite"],
methods:
{
/* eslint-disable no-console */
deleteLocalite() {
http
.delete("/localite/" + this.localite.id)
.then(response => {
console.log(response.data);
this.$emit("refreshData");
this.$router.push('/localite');
})
.catch(e => {
console.log(e);
});
}
/* eslint-enable no-console */
}
};
</script>
Thanks
Props are used to pass data down in the component hierarchy. If you want to get data from an API and pass it to several components I would suggest getting the list of Localite's in a parent component and then pass it via props. A rule of thumb is to have more logic in parent components and less logic in child components.
Example:
<template>
<div>
<localite :localite="listOfLocalites" />
</div>
</template>
Then you can in your localite component get the the prop via props: ["localite"]
In an example of a Vue wizard form I tried to add form validation with Joi. How do I set this up logically? The goal is to controll the fields before moving to the second and last page with the next() method. Because of the simplicity of this wizard form, I don't want to change to VueFormWizard. To increase the code I erased a lot of fields etc..
<template>
<div>
<div v-if="errorMessage" class="alert alert-danger" role="alert">
{{errorMessage}}
</div>
<form>
<div v-if="step ===1 ">
<div class="form-group">
<label for="title">Title</label>
<input v-model="example.title"
type="text"
class="form-control"
id="title" />
</div>
<button #click.prevent="next()">Next step</button>
</div>
<div v-if="step === 2">
<div class="form-group">
<label for="userName">Email.</label>
<input v-model="example.userName"
type="email"
class="form-control"
id="userName" />
</div>
<button #click.prevent="prev()">Go back</button>
<button #click.prevent="createExample" type="submit" class="btn btn-primary">Submit</button>
</div>
</form>
</div>
</template>
<script>
import Joi from 'joi'
const schema = Joi.object().keys({
title: Joi.string().alphanum().min(2).max(40).required(),
userName: Joi.string().email(),
})
export default {
data: () => ({
step: 1,
errorMessage: false,
example: {
title: '',
userName: ''
}
}),
watch: {
example: {
handler () {
this.errorMessage = ''
},
deep: true
}
},
methods: {
prev () {
this.step--
},
next () {
this.step++
if (this.validUser()) {
return false
}
},
createExample () {
// Post request
},
validUser () {
const result = Joi.validate(this.huismap, schema)
return true
if (result.error.message.includes('title')) {
this.errorMessage = 'Vul een titel in van min 2 karakters'
return false
}
}
}
</script>
You can make use of browser validation if you set it up like this:
<form #submit.prevent="submitMyForm">
<input v-model="form.title" required minlength="4" maxlength="20" />
<button type="submit">Submit</button>
</form>
Now your browser will prevent you from submitting the form if title is empty, if the length is less than 4 or greater than 20.
This solution can do a lot of stuff, even regex checking:
https://developer.mozilla.org/en-US/docs/Learn/HTML/Forms/Form_validation#Validating_against_a_regular_expression
However this is limited to a small set of checks and is not supported by older browsers. If you need very specific validation you'd have to use a custom solution, which is described here https://v2.vuejs.org/v2/cookbook/form-validation.html.
I am trying to create a frontend for a Spring Boot application and I chose React but I do not have much experience with React or JavaScript.
So I have a form that I am trying to use to send a post request but when I press the submit button, nothing seems to happen. I assume its my onSubmit handler that's the problem but I don't know what is wrong with it. When I send the POST request manually it works fine so I don't think it's the REST API thats causing an issue.
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import axios from 'axios';
import { Link } from 'react-router-dom';
class Create extends Component {
constructor() {
super();
this.state = {
name: '',
email: '',
title: '',
description: ''
};
}
onChange = (e) => {
const state = this.state
state[e.target.name] = e.target.value;
this.setState(state);
}
onSubmit = (e) => {
e.preventDefault();
const { name, email, title, description } = this.state;
axios.post('/create', { name, email, title, description })
.then((result) => {
this.props.history.push("/")
});
}
render() {
const { name, email, title, description } = this.state;
return (
<div class="container">
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">
Send Message
</h3>
</div>
<div class="panel-body">
<h4><Link to="/"><span class="glyphicon glyphicon-th-list" aria-hidden="true"></span> Message List</Link></h4>
<form onSubmit={this.onSubmit}>
<div class="form-group">
<label for="name">Name:</label>
<input type="text" class="form-control" name="name" onChange={this.onChange}/>
</div>
<div class="form-group">
<label for="email">Email:</label>
<input type="text" class="form-control" name="email" onChange={this.onChange}/>
</div>
<div class="form-group">
<label for="title">Title:</label>
<input type="text" class="form-control" name="title" onChange={this.onChange}/>
</div>
<div class="form-group">
<label for="description">Description:</label>
<input type="text" class="form-control" name="description" onChange={this.onChange}/>
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
</div>
</div>
</div>
);
}
}
export default Create;
The first rule of React is, You do not update state property directly (or React wouldn't know that the state has changed).
It's not easy to tell how React would behave if you do so.
So instead of setting the state value directly,
onChange = (e) => {
const state = this.state
state[e.target.name] = e.target.value;
this.setState(state);
}
Change it like this and try to submit again.
onChange = (e) => {
const state = this.state
this.setState({[e.target.name]: e.target.value});
}
I'm building an app which uses vue.js and Laravel 5 to persist data into a database. So far, it can successfully save data.
My problem
I'm having trouble with displaying errors when the user validation fails using the 'out of the box' authorisation that Laravel has. I keep getting the error:
[Vue warn]: Error when evaluating expression "form.errors.length > 0"
(referring to errors.js in my code below)
Piecing it together
So how this should work...a user enters their details into the registration page and Vue (using vue-resource) makes an AJAX request to the 'out of the box' Laravel AuthController#postRegister method. On error, Laravel nicely spits out the JSON error messages we all expect. Now in theory, the sendRegistration method within my subscription.js file should detect the errors that Laravel spits out (I've tested this with console.log's and it works) and pass them into the errors.js component to display the errors within the <spark-errors> tags. In order to do this, it uses a setErrorsOnForm: function within my <head> tag. However it's not working as expected and I cannot workout why.
My code
My code consists of a registration page:
<!DOCTYPE html>
<html lang="en">
<head>
<!-- Laravel Spark Globals -->
<script>
window.Spark = {
// Laravel CSRF Token
csrfToken: '{{ csrf_token() }}',
// Flatten errors and set them on the given form
setErrorsOnForm: function (form, errors) {
if (typeof errors === 'object') {
form.errors = _.flatten(_.toArray(errors));
} else {
form.errors.push('Something went wrong. Please try again.');
}
}
}
</script>
</head>
<body>
<div id="spark-app">
<spark-subscription-register-screen inline-template>
<div class="panel panel-default">
<div class="panel-heading">Your Information</div>
<div class="panel-body">
<spark-errors form="#'{'{ registerForm '}'}"></spark-errors>
<form class="form-horizontal" role="form" id="subscription-basics-form">
<div class="form-group">
<label class="col-md-4 control-label">Your Name</label>
<div class="col-md-6">
<input type="text" class="form-control spark-first-field" name="name" v-model="registerForm.name">
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label">E-Mail Address</label>
<div class="col-md-6">
<input type="email" class="form-control" name="email" v-model="registerForm.email">
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label">Password</label>
<div class="col-md-6">
<input type="password" class="form-control" name="password" v-model="registerForm.password">
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label">Confirm Password</label>
<div class="col-md-6">
<input type="password" class="form-control" name="password_confirmation" v-model="registerForm.password_confirmation">
</div>
</div>
<div v-if="freePlanIsSelected">
<div class="form-group">
<div class="col-sm-6 col-sm-offset-4">
<div class="checkbox">
<label>
<input type="checkbox" v-model="registerForm.terms"> I Accept The Terms Of Service
</label>
</div>
</div>
</div>
<div class="form-group">
<div class="col-sm-6 col-sm-offset-4">
<button type="submit" class="btn btn-primary" v-on:click="register" :disabled="registerForm.registering">
<span v-if="registerForm.registering">
<i class="fa fa-btn fa-spinner fa-spin"></i> Registering
</span>
<span v-if=" ! registerForm.registering">
<i class="fa fa-btn fa-check-circle"></i> Register
</span>
</button>
</div>
</div>
</div>
</form>
</div>
</div>
</spark-subscription-register-screen inline-template>
</div>
</body>
</html>
From a vue.js perspective there is a subscription.js file:
Vue.component('spark-subscription-register-screen', {
/*
* Initial state of the component's data.
*/
data: function () {
return {
registerForm: {
nhs_org: '', team_name: '', name: '', email: '', password: '', password_confirmation: '',
plan: '', terms: false, coupon: null, invitation: null,
stripe_token: null, errors: [], registering: false
},
};
},
methods: {
/*
* Initialize the registration process.
*/
register: function(e) {
var self = this;
e.preventDefault();
this.registerForm.errors = [];
this.registerForm.registering = true;
return this.sendRegistration();
},
/*
* After obtaining the Stripe token, send the registration to Spark.
*/
sendRegistration: function() {
this.$http.post('/register', this.registerForm)
.success(function(response) {
window.location = '/';
})
.error(function(errors) {
this.registerForm.registering = false;
Spark.setErrorsOnForm(this.registerForm, errors);
});
},
}
});
and there is an errors.js Vue component:
/*
* Common Error Display Component.
*/
Vue.component('spark-errors', {
props: ['form'],
template: "<div><div class='alert alert-danger' v-if='form.errors.length > 0'>\
<strong>Whoops!</strong> There were some problems with your input.<br><br>\
<ul>\
<li v-for='error in form.errors'>\
{{ error }}\
</li>\
</ul>\
</div></div>"
});
Now the Vue files which piece all of this together (in the correct order):
app.js:
require('./core/dependencies');
if ($('#spark-app').length > 0) {
new Vue(require('./core/spark.js'));
}
core/dependencies.js:
/*
* Load Vue & Vue-Resource.
*
*/
if (window.Vue === undefined) window.Vue = require('vue');
require('vue-resource');
Vue.http.headers.common['X-CSRF-TOKEN'] = Spark.csrfToken;
/*
* Load Underscore.js, used for map / reduce on arrays.
*/
if (window._ === undefined) window._ = require('underscore');
/*
* Load jQuery and Bootstrap jQuery, used for front-end interaction.
*/
if (window.$ === undefined || window.jQuery === undefined) window.$ = window.jQuery = require('jquery');
require('bootstrap-sass/assets/javascripts/bootstrap');
core/spark.js:
/*
* Load the Spark components.
*/
require('./components');
/**
* Export the Spark application.
*/
module.exports = {
el: '#spark-app',
/*
* Bootstrap the application. Load the initial data.
*/
ready: function () {
$(function() {
$('.spark-first-field').filter(':visible:first').focus();
});
}
}
and core/components.js:
require('./../auth/registration/subscription');
require('./../common/errors');
I had the same issue, and instead of using the out of the box errors from spark, I defined my own component:
<template>
<div v-if="errors">
<div class="alert alert-danger" v-if="formattedErrors.length > 0">
<strong>Whoops!</strong> There were some problems with your input.<br><br>
<ul>
<li v-for="error in formattedErrors">
{{ error }}
</li>
</ul>
</div>
</div>
</template>
<script>
export default {
props: ['errors'],
computed: {
formattedErrors() {
return this.format(this.errors);
}
},
methods: {
format(errors) {
if (typeof errors === 'undefined') {
return [];
}
if (typeof errors === 'object') {
return _.flatten(_.toArray(errors));
}
}
}
}
</script>
Then you bind in your html:
<form-errors :errors="registerForm.errors"></form-errors>
It makes sense because your component just need the to now about errors, and nothing else about the registerForm.
Hope this helps.