Importing Chance JS library in Vue.js - javascript

I have 2 views for adding data to a database, one for songs and one for genres. However, I want to populate the input fields with random data, but I don't know why importing chance in genres, but not in songs, makes songs working, but not genres page.
Genre View:
<template>
<div>
<input type="text" id="genre-name" placeholder="Name" v-model="name" /><br />
<input type="text" id="genre-country" placeholder="Country" v-model="country" /><br />
<input type="text" id="genre-year" placeholder="Year" v-model="year" /><br />
<button #click="addGenre" id="genre-button">Add Genre</button>
</div>
</template>
<script>
import { requestOptions, base_url } from '#/utils/requestOptions';
//var chance = require('chance').Chance(); this works for both, when importing only in one file
import {chance} from "chance"; //<= this is the line I am talking about
export default {
data() {
return {
name: chance.radio(),
country: chance.country({ full: true }),
year: chance.year()
}
},
methods: {
addGenre() {
//...
}
}
}
</script>
Song View:
<template>
<div>
<input type="text" id="name" placeholder="Name" v-model="name" /><br />
<input type="text" id="author" placeholder="Author" v-model="author" /><br />
<input type="text" id="country" placeholder="Country" v-model="country" /><br />
<input type="text" id="duration" placeholder="Duration" v-model="duration" /><br />
<input type="text" id="views" placeholder="Views" v-model="views" /><br />
<input type="text" id="genre" placeholder="Genre" v-model="genre" /><br />
<button #click="addSong">Add Song</button>
</div>
</template>
<script>
import { requestOptions, base_url } from '#/utils/requestOptions';
//this is working without importing chance
export default {
data() {
return {
name: chance.word(),
author: chance.last(),
country: chance.country({ full: true }),
duration: chance.minute(),
views: chance.integer({ min: 0, max: 100000000 }),
genre: chance.radio()
}
},
methods: {
addSong() {
//...
}
}
}
</script>
The error message I am getting when I am opening the Genre View is:
TypeError: undefined is not an object (evaluating 'chance__WEBPACK_IMPORTED_MODULE_1__.chance.radio')
So I want to know why is it working on the Song View?
If I delete the import line, it will not work in any view.

Related

How to run http post request in vue.js

I'm just learning Vue and I'm making http post request in vue.js and flask as the backend. When I run the program am getting 404 error code. I do not know how to debug the problem but when I test using postman it is working perfect. when I use axios but I am encountering 404.
Below is my frontend code :
<template>
<div>
<h3> {{msg}}</h3>
<p> we help you drive your business with the modern technology. </p>
<div class="alert alert-success" v-if="isSuccess">
Post Created Successfully
</div>
<form #submit.prevent='OnCreateTown' class="add-town">
<div class="form-control">
<label>task</label>
<input type="text" class ="form-control" v-model="text" name="text" placeholder="name" />
<input type="number" step="any" class ="form-control" v-model="text" name="text" placeholder="elevation" />
<input type="text" class ="form-control" v-model="text" name="text" placeholder="grid reference" />
<input type="number" step="any" class ="form-control" v-model="text" name="text" placeholder="longitude" />
<input type="number" step="any" class ="form- control" v-model="text" name="text" placeholder="latitude" />
<input type="text" class ="form- control" v-model="text" name="text" placeholder="postcode_secto" />
<input type="text" class ="form- control" v-model="text" name="text" placeholder="nuts_region" />
<input type="number" step="any" class ="form- control" v-model="text" name="text" placeholder="northing" />
<input type="number" step="any" class ="form- control" v-model="text" name="text" placeholder="easting" />
<input type="text" class ="form- control" v-model="text" name="text" placeholder="town_type" />
<input type="text" class ="form- control" v-model="text" name="text" placeholder="local_government_area" />
</div>
<input type="submit" value="submit" class="btn btn-block" />
</form>
</div>
</template>
<script>
import axios from 'axios';
export default {
name: 'CreateTown',
props:{
msg: String
},
data(){ // the data expected from the form
return{
form: {
name: '',
elevation: '',
grid_reference: '',
longitude: '',
latitude: '',
postcode_secto:'',
nuts_region:'',
northing:'',
easting :'',
town_type:'',
local_government_area:'',
isSuccess: false,
}
};
},
methods:{
OnCreateTown(){ // when the submit button is clicked, the form data is sent to the backend
axios.post('https://david.darwinist.io/proxy/5000/town.json', this.form)
.then((response) => {// checking response in the console
this.isSuccess = true;
console.log(response.data);
this.$emit('towncreated');
}).catch(err =>{
console.log(err)});
},
},
};
and this is my backend :
def addTown(session, town_dict):
# Try and get the Country from the database. If error (Except) add to the database.
town = Town()
# Add attributes
town.county = addGetCounty(session, town_dict["county"], town_dict["nation"])
town.name = town_dict["name"]
town.grid_reference = town_dict["grid_reference"]
town.easting = town_dict["easting"]
town.northing = town_dict["northing"]
town.latitude = town_dict["latitude"]
town.longitude = town_dict["longitude"]
town.elevation = town_dict["elevation"]
town.postcode_sector = town_dict["postcode_sector"]
town.local_government_area = town_dict["local_government_area"]
town.nuts_region = town_dict["nuts_region"]
town.town_type = town_dict["town_type"]

set knock date two days before delivery date in vue.js

I am new to vue.js.
I have a form that has two date input fields like Delivery date and Knock date.
I want to set knock date automatically two days before delivery date. For example if the delivery date is 20/9/2021, the knock date should be 18/9/2021.
How to implement this in vue.js ?
Here are the form fields given below:
<template>
<form>
<label for="">PO Delivery Date</label>
<input
class="form-control"
type="date"
v-model="PO_DeliveryData"
v-validate="'required'"
placeholder="PO Delivery Date"
/><br />
<label for="">Knock Date</label>
<input
class="form-control"
type="date"
v-model="knock_Date"
v-validate="'required'"
placeholder="Knock Date"
/><br />
</form>
</template>
<script>
export defaults:{
}
</script>
Try like following snippet:
new Vue({
el: '#demo',
data() {
return {
PO_DeliveryData: '',
knock_Date: ''
}
},
watch: {
PO_DeliveryData() {
let d = new Date(this.PO_DeliveryData);
d.setDate(d.getDate() - 2);
this.knock_Date = d.toISOString().slice(0, 10)
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="demo">
<form>
<label for="">PO Delivery Date</label>
<input
class="form-control"
type="date"
v-model="PO_DeliveryData"
placeholder="PO Delivery Date"
/><br />
<label for="">Knock Date</label>
<input
class="form-control"
type="date"
v-model="knock_Date"
placeholder="Knock Date"
/><br />
</form>
</div>
It's easy to calculate with momentjs
<template>
<form>
<label for="">PO Delivery Date</label>
<input
v-model="deliveryDate"
class="form-control"
type="date"
placeholder="PO Delivery Date"
/><br />
<label for="">Knock Date</label>
<input
:value="knockDate"
class="form-control"
type="date"
placeholder="Knock Date"
/>
<pre>deliveryDate: {{ deliveryDate }}</pre>
<pre>knockDate: {{ knockDate }}</pre>
</form>
</template>
<script>
import moment from "moment";
export default {
name: "App",
data: () => {
return {
deliveryDate: "",
knockDate: "",
};
},
watch: {
deliveryDate(val) {
if (val) {
this.knockDate = moment(val, "YYYY-MM-DD")
.subtract(2, "day")
.format("YYYY-MM-DD");
} else {
this.knockDate = "";
}
},
},
};
</script>

Enable/Disable button with vueJs

new Vue({
el: '#app',
data: {
terms: false,
fullname: false,
mobile: false,
area: false,
city: false,
},
computed: {
isDisabled: function(){
return !this.terms && !this.fullname && !this.mobile && !this.area && !this.city;
}
}
})
<div id="app">
<p>
<label for='terms'>
<input id='terms' type='checkbox' v-model='terms' /> I accept terms!!!
<input id="fullname" type='text' v-modal='fullname'/> name
<input id="mobile" type='text' v-modal='mobile'/> mobile
<input id="area" type='text' v-modal='area'/> area
<input id="city" type='text' v-modal='city'/> city
</label>
</p>
<button :disabled='isDisabled'>Send Form</button>
</div>
Until user fill all the details, button should be disabled.
But Issue with this is if i click on checkbox directly button is enabling without checking for other fields
There are many problems in your code and i will list them one by one.
data property should be a function.
fullname , mobile , ... are bound to input type="text" so empty string is better for initial value.
there are typos in your v-modal
there is a mistake in your logical formula for isDisabled
so the final code should be like this:
new Vue({
el: '#app',
data() {
return {
terms: false,
fullname:'',
mobile: '',
area: '',
city: '',
};
},
computed: {
isDisabled: function(){
return !this.terms || !this.fullname || !this.mobile || !this.area || !this.city;
}
}
})
<div id="app">
<p>
<label for='terms'>
<input id='terms' type='checkbox' v-model='terms' /> I accept terms!!!
<input id="fullname" type='text' v-model='fullname'/> name
<input id="mobile" type='text' v-model='mobile'/> mobile
<input id="area" type='text' v-model='area'/> area
<input id="city" type='text' v-model='city'/> city
</label>
</p>
<button :disabled='isDisabled'>Send Form</button>
</div>
I highly recommend you to use IDE or eslint.

Problem transfer list Localite to Add User in a selectBox

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"]

React app error: `Uncaught TypeError: Cannot read property 'refs' of null`

I'll just post the code of the component:
class AddPostForm extends React.Component {
createPost(event) {
event.preventDefault();
let post = {
title : this.refs.title.value,
name : this.refs.name.value,
desc : this.refs.desc.value,
image : this.refs.image.value
}
this.props.addPost(post);
this.refs.postForm.reset();
}
render() {
return (
<div className="callout secondary form-area">
<h5>Add a Post to the React Blog</h5>
<form className="post-edit" ref="postForm" onSubmit={this.createPost}>
<label>Post Title
<input type="text" ref="title" placeholder="Post Title" required/>
</label>
<label>Author Name
<input type="text" ref="name" placeholder="Full Name required" required/>
</label>
<label>Post Body
<textarea
ref="desc"
placeholder="Write your post here" required/>
</label>
<label>Image URL - <span className="highlight">use this one to test 'http://bit.ly/1P9prpc'</span>
<input type="url" ref="image" placeholder="The URL of the featured image for your post" required/>
</label>
<button type="submit" className="button">Add Post</button>
</form>
</div>
)
}
}
When the function createPost is triggered, the console logs an error: Uncaught TypeError: Cannot read property 'refs' of null.
Yet when I transform the code back to ES5, it works:
var AddPostForm = React.createClass({
createPost : function(event) {
event.preventDefault();
// take the data from the form and create an object
var post = {
title : this.refs.title.value,
name : this.refs.name.value,
desc : this.refs.desc.value,
image : this.refs.image.value
}
// add the post to the App State
this.props.addPost(post);
this.refs.postForm.reset();
},
render : function() {
return (
<div className="callout secondary form-area">
<h5>Add a Post to the React Blog</h5>
<form className="post-edit" ref="postForm" onSubmit={this.createPost}>
<label>Post Title
<input type="text" ref="title" placeholder="Post Title" required/>
</label>
<label>Author Name
<input type="text" ref="name" placeholder="Full Name required" required/>
</label>
<label>Post Body
<textarea
ref="desc"
placeholder="Write your post here" required/>
</label>
<label>Image URL - <span className="highlight">use this one to test 'http://bit.ly/1P9prpc'</span>
<input type="url" ref="image" placeholder="The URL of the featured image for your post" required/>
</label>
<button type="submit" class="button">Add Post</button>
</form>
</div>
)
}
});
You should set this for createPost, because with ES2015 classes in React there is no autobinding, but this feature exists when you use React.createClass
class AddPostForm extends React.Component {
constructor(props) {
super(props);
this.createPost = this.createPost.bind(this);
}
....
}
Autobinding

Categories

Resources