I'm working on a project in Laravel. I'm using vue.js components inside Laravel blade files. So far, I have a component called "Index.vue" which is loaded from index.blade.php. Another component called "create.vue" which is loaded from "create.blade.php". The problem is Create.vue component is not displaying when I click the button "create a new service" from index.blade.php. All the other Vue.js components works fine, but this issue is only for that particular component. I have tried to run "npm run dev" and changed webpack.mix.js file but it didn't solve my problem. I don't have any issues on my local machine, only in the production environment.
index.js
<x-admin-master>
#section('content')
<div class="container">
<div id="app">
<Index></Index>
Create a new service
</div>
</div>
#endsection
</x-admin-master>
Webpack.js
const mix = require('laravel-mix');
/*
|--------------------------------------------------------------------------
| Mix Asset Management
|--------------------------------------------------------------------------
|
| Mix provides a clean, fluent API for defining some Webpack build steps
| for your Laravel application. By default, we are compiling the Sass
| file for the application as well as bundling up all the JS files.
|
*/
mix.js('resources/js/app.js', 'public/js')
.vue()
.sass('resources/sass/app.scss', 'public/css')
.copy(
'node_modules/#fortawesome/fontawesome-free/webfonts',
'public/webfonts'
)
.sourceMaps()
.version(['public/js/app.js']);
Create.vue
<template>
<div>
<p v-if="errors.length">
<b>Please correct the following error(s):</b>
<ul>
<li v-for="error in errors">{{ error }}</li>
</ul>
</p>
<form #submit.prevent="addService" action="/api/services" method="POST">
<div class="form-group">
<label for="name">Name: </label>
<input type="text" name="name" class="form-control" id="name" placeholder="Enter service name" v-model="services.name">
</div>
<div class="form-group">
<label for="vendor">Vendor: </label>
<select class="form-control" name="vendor" placeholder="select vendor" v-model="services.vendor" value="Select vendor">
<option name="vendor" :value="service.vendor.id" v-for="service in services">{{service.vendor.name}}</option>
</select>
</div>
<div class="form-group">
<label for="service">Description: </label>
<textarea class="form-control" id="desc" name="desc" rows="3" v-model="services.desc"></textarea>
</div>
<div class="d-flex flex-row hour-price" v-if="hourAndPrice">
<div class="form-group">
<input type="number" name="hours" class="form-control" #click="fixedPrice = false" id="hours" placeholder="Hours" v-model="services.hours">
</div>
<div class="form-group">
<input type="number" name="price" class="form-control" #click="fixedPrice = false" id="price" placeholder="Price" v-model="services.price">
</div>
</div>
<div class="d-flex flex-row fixed-price" v-if="fixedPrice">
<div class="form-group">
<input type="number" #click="hourAndPrice = false" name="fixed_price" class="form-control" id="price" placeholder="Enter fixed price" v-model="services.fixed_price">
</div>
</div>
<input type="submit" value="Add Service" class="btn btn-primary">
<div class="btn-toolbar d-flex justify-content-end">
Services
</div>
</form>
</div>
</template>
<script>
export default {
data(){
return {
//vendors: this.vendors,
//projects: this.projects,
hourAndPrice: true,
fixedPrice: true,
services: [],
errors: [],
services: {
name: null,
vendor: null,
desc: null,
hours: null,
price: null,
fixed_price: null
}
}
},
methods: {
addService(){
let ok = ''
if(this.services.name && this.services.vendor){
ok = true
}
if(!this.services.name){
this.errors.push('Service name is required')
}
if(!this.services.vendor){
this.errors.push('Vendor ID is required')
}
if(ok) {
axios.get('/sanctum/csrf-cookie').then(response => {
axios.post('/api/services', {
name: this.services.name,
vendor: this.services.vendor,
desc: this.services.desc,
hours: this.services.hours,
price: this.services.price,
fixed_price: this.services.fixed_price,
})
.then(function (response) {
console.log(response)
window.location.href = '/admin/services';
})
.catch(function (error) {
console.log(error);
});
});
}
},
loadServices: function(){
axios.get('/api/services/getservicedata')
.then(response => {
this.services = response.data;
})
.catch(function(error){
console.log(error);
});
}
},
mounted(){
console.log('Successfully mounted!');
this.loadServices()
}
}
</script>
Related
this is the code I've implemented in vue.js
I was trying to add a new employee to the firebase database.
the code was working until I wrote the methods and initialized the data section
when I tried going back steps where the code was running it was still giving runtime error
<template>
<div class="container-fluid">
<center><h1>New Employee</h1></center>
<form #submit.prevent="adds" class="form">
<label>Enter Name</label>
<input type="text" class="form-control" v-modle="name">
<label>Enter Employee ID</label>
<input type="text" class="form-control" v-modle="emp_id">
<label>Enter Department</label>
<input type="text" class="form-control" v-modle="dep">
<label>Enter Position</label>
<input type="text" class="form-control" v-modle="position" >
<router-link to="/" class="btn btn-danger btn-lg">Cancel</router-link>
<button type="submit" class="btn btn-outline-success btn-lg">Submit</button>
</form>
</div>
</template>
<script>
import db from '../components/firebaseinit.js'
export default {
name:"newEmployee",
data(){
return{
name: null,
emp_id: null,
dep: null,
position: null
}
},
methods:{
adds(){
db.collection('employee').add({
emp_id: parseInt(this.emp_id),
name: this.name,
dep: this.dep,
position: this.position
}).then(this.router.push("/")).catch(err => console.log(err))
}
}
}
</script>
I found the problem with my code at line 42
then(this.router.push("/")).catch(err => console.log(err))
The right way to call router is by $ the code would be replaced by
then(() => this.$router.push("/")).catch(err => console.log(err))
just like the title said i created registration form using react js, at first it's working when finish fill the form it link to another page. But the problem is after user fill all the form it suppose to automatically send email verification and i didn't get any email verification. can anyone help me with this problem, i still new using react jS. any help would be appreciated...
this is my code if anyone wondering:
import React, { Component } from 'react';
import {Redirect, Link, router } from 'react-router-dom';
import './SignUp.css';
import axios from 'axios';
export default class Login extends Component {
componentDidMount() {
window.scrollTo(0, 0)
}
constructor(props) {
super(props);
this.state={
company: '',
province: '',
city: '',
website: '',
address: '',
contact:'',
password:'',
email:'',
errors: {}
}
this.handleChangeCompany = this.handleChangeCompany.bind(this);
this.handleChangeWebsite = this.handleChangeWebsite.bind(this);
this.handleChangeProvince = this.handleChangeProvince.bind(this);
this.handleChangeCity= this.handleChangeCity.bind(this);
this.handleChangeAddress = this.handleChangeAddress.bind(this);
this.handleChangeMobile = this.handleChangeMobile.bind(this);
this.handleChangeEmail = this.handleChangeEmail.bind(this);
this.handleChangePassword = this.handleChangePassword.bind(this);
this.submituserRegistrationForm = this.submituserRegistrationForm.bind(this);
}
handleChangeWebsite(e) {
this.setState({website:e.target.value});
}
handleChangeProvince(e) {
this.setState({province:e.target.value});
}
handleChangeCity(e) {
this.setState({city:e.target.value});
}
handleChangeCompany(e) {
this.setState({company:e.target.value});
}
handleChangeAddress(e) {
this.setState({address:e.target.value});
}
handleChangeEmail(e) {
this.setState({email:e.target.value});
}
handleChangeMobile(e) {
this.setState({contact:e.target.value});
}
handleChangePassword(e) {
this.setState({password:e.target.value});
}
submituserRegistrationForm(e) {
e.preventDefault();
if (this.validateForm()) {
var apiBaseUrl = "http://THIS_IS_MY_API_:3000";
var data={
"query":"mutation{ createProfile( profileInput :{company: \""+this.state.company+"\", address: \""+this.state.address+"\", email: \""+this.state.email+"\", contact: \""+this.state.contact+"\", province: \""+this.state.province+"\", city: \""+this.state.city+"\", website: \"\", operational: 24, password: \""+this.state.password+"\"}){ _id company address city province email contact website logo createdAt updatedAt } }"
}
/*console.log(data);*/
var headers = {
'Content-Type': 'application/json',
}
axios.post(apiBaseUrl, data, {headers: headers}).then(function (response) {
if(response.data.data){
console.log(response.data.data);
localStorage.setItem("u_code", encodeURIComponent(JSON.stringify(response.data.data)));
localStorage.setItem('is_done', true);
window.location.href = "/login";
console.log("Sign Up successfull");
}else{
alert(response.data.message);
}
}).catch(function (error) {
console.log(error);
});
}
}
validateForm() {
let errors = {};
let formIsValid = true;
return formIsValid;
}
render() {
return (
<div className="container-fluid">
<div className="row no-gutter">
<div className="d-none d-md-flex col-md-4 col-lg-6 bg-image" />
<div className="col-md-8 col-lg-6">
<div className="login d-flex align-items-center py-5">
<div className="container">
<div className="row">
<div className="col-md-9 col-lg-8 mx-auto">
<h3 className="login-heading mb-4">Sign Up Now!</h3>
<form method="post" name="userRegistrationForm" onSubmit= {this.submituserRegistrationForm}>
<br></br>
<h5 className="login-heading mb-4"><u>Company</u></h5>
<div className="form-label-group">
<input name="company" value={this.state.company} onChange={this.handleChangeCompany} id="company" className="form-control" placeholder="Company" required autofocus />
<label htmlFor="company">Company</label>
</div>
<br></br>
<h5 className="login-heading mb-4"><u>City</u></h5>
<div className="form-label-group">
<input name="City" value={this.state.city} onChange={this.handleChangeCity} className="form-control" placeholder="City" required autofocus />
<label>City</label>
</div>
<br></br>
<h5 className="login-heading mb-4"><u>Address</u></h5>
<div className="form-label-group">
<input name="address" value={this.state.address} onChange={this.handleChangeAddress} className="form-control" placeholder="Address" required autofocus />
<label>Address</label>
</div>
<br></br>
<h5 className="login-heading mb-4"><u>Province</u></h5>
<div className="form-label-group">
<input name="Province" value={this.state.province} onChange={this.handleChangeProvince} className="form-control" placeholder="Province" required autofocus />
<label >Province</label>
</div>
<br></br>
<h5 className="login-heading mb-4"><u>Email Address</u></h5>
<div className="form-label-group">
<input name="email" value={this.state.email} onChange={this.handleChangeEmail} className="form-control" placeholder="Email" required autofocus />
<label>Email</label>
</div>
<br></br>
<h5 className="login-heading mb-4"><u>Contact</u></h5>
<div className="form-label-group">
<input name="contact" value={this.state.contact} onChange={this.handleChangeMobile} className="form-control" placeholder="Contact Number" required autofocus />
<label>Contact</label>
</div>
<br></br>
<h5 className="login-heading mb-4"><u>Password</u></h5>
<div className="form-label-group">
<input type="password" value={this.state.password} onChange={this.handleChangePassword} name="password" id="inputPassword" className="form-control" placeholder="Password" required />
<label htmlFor="inputPassword">Password</label>
</div>
<br></br>
<button value="Login" className="btn btn-lg btn-primary btn-block btn-login text-uppercase font-weight-bold mb-2" type="submit">Sign Up</button>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
);
}
}
it's seems nothing wrong with the code it just i put Json web token in the wrong place.
the correct one is like this :
const getJWT = () => {
return localStorage.getItem('token');
};
const jwt = getJWT();
if (!jwt){
window.location.href = "/";
};
instead of this, it created another token and thats why the server did not recognize because of unrecognized token :
localStorage.setItem("u_code", encodeURIComponent(JSON.stringify(response.data.data)));
localStorage.setItem('is_done', true);
in the header i just put jwt like this :
'Authorization' : 'Tesla '+jwt+''
First of all I would like to apologize if the answer to my question is obvious, however since I'm still pretty new to Vue.js, I'm getting really stuck here and I need help.
I got an authentication system and if the user wants to register without putting in an username, I would like to show an bootstrap alert. The code looks like this right now:
<template>
<div class="container">
<div class="row">
<div class="col-md-6 mt-5 mx-auto">
<form v-on:submit.prevent="register">
<h1 class="h3 mb-3 font-weight-normal">Register</h1>
<div class="form-group">
<label for="username">Username</label>
<input
type="text"
v-model="username"
class="form-control"
name="username"
placeholder="Please choose your username"
>
</div>
<div class="form-group">
<label for="email">Email Address</label>
<input
type="email"
v-model="email"
class="form-control"
name="email"
placeholder="Please enter your email address"
>
</div>
<div class="form-group">
<label for="password">Password</label>
<input
type="password"
v-model="password"
class="form-control"
name="password"
placeholder="Please choose your password"
>
</div>
<button class="btn btn-lg btn-primary btn-block" type="submit">Register</button>
</form>
<div>
<b-alert variant="success" show>Example alert</b-alert>
</div>
<div>
<b-alert variant="danger" :show="showAlert">Example Alert!</b-alert>
</div>
</div>
</div>
</div>
</template>
<script>
import axios from "axios";
import router from "../router";
export default {
data() {
return {
username: "",
email: "",
password: "",
showAlert: false };
},
methods: {
register() {
axios
.post("/user/register", {
username: this.username,
email: this.email,
password: this.password
})
.then(res => {
if (!res.data.username) {
// show an alert, I would like to do something similar to "showAlert = true;"
} else {
// redirect to login
}
})
.catch(err => {
console.log(err);
});
}
}
};
</script>
<style scoped>
#import "../assets/css/reglog.css";
#import "../assets/css/modal.css";
</style>
However I'm not sure how to access the showAlert variable neither how to change its value in the if-statement. The only thing that I know here is that if I change the showAlert manually in the code (line 9 counting from the script tag) from false to true, the page does react and shows the alert when wanted.
I'm sorry if you need more information or if something is unclear, I'm a bit tired and stuck with this for some hours, not gonna lie.
You can access showAlert variable following: this.showAlert = true
.then(res => {
if (!res.data.username) {
this.showAlert = true; // update showAlert
} else {
// redirect to login
}
})
I'm trying to write a custom form control in Vue.js to learn how to package together multiple form inputs into a single custom component.
My project setup looks like this (standard webpack-simple vue cli setup):
$ tree -L 1
.
├── README.md
├── index.html
├── node_modules
├── package.json
├── src
└── webpack.config.js
Here's my top level Vue instance .vue file:
// App.vue
<template>
<div class="container">
<form v-if="!submitted" >
<div class="row">
<div class="col-xs-12 col-sm-8 col-sm-offset-2 col-md-6 col-md-offset-3">
<form>
<fullname v-model="user.fullName"></fullname>
<div class="form-group">
<label for="email">Email:</label>
<input id="email" type="email" class="form-control" v-model="user.email">
<label for="password">Password:</label>
<input id="password" type="password" class="form-control" v-model="user.password">
</div>
<fieldset class="form-group">
<legend>Store data?</legend>
<div class="form-check">
<label class="form-check-label">
<input type="radio" class="form-check-input" name="storeDataRadios" id="storeDataRadios1" value="true" checked v-model="user.storeData">
Store Data
</label>
</div>
<div class="form-check">
<label class="form-check-label">
<input type="radio" class="form-check-input" name="storeDataRadios" id="storeDataRadios2" value="false" v-model="user.storeData">
No, do not make my data easily accessible
</label>
</div>
</fieldset>
</form>
<button class="btn btn-primary" #click.prevent="submitForm()">Submit</button>
</div>
</div>
</form>
<hr>
<div v-if="submitted" class="row">
<div class="col-xs-12 col-sm-8 col-sm-offset-2 col-md-6 col-md-offset-3">
<div class="panel panel-default">
<div class="panel-heading">
<h4>Your Data</h4>
</div>
<div class="panel-body">
<p>Full Name: {{ user.fullName }}</p>
<p>Mail: {{ user.email }}</p>
<p>Password: {{ user.password }} </p>
<p>Store in Database?: {{ user.storeData }}</p>
</div>
</div>
</div>
</div>
</div>
</template>
<script>
import FullName from './FullName.vue';
export default {
data() {
return {
user: {
fullName: 'John Smith',
email: '',
password: '',
storeData: true,
},
submitted: false
}
},
methods: {
submitForm() {
this.submitted = true;
},
},
components: {
'fullname' : FullName,
}
}
</script>
<style>
</style>
And here's the custom component file:
<template>
<div class="form-group">
<label for="firstName">First name:</label>
<input id="firstName" type="text" class="form-control" :value="first" #input="emitChange(true, $event)">
<label for="lastName">Last name:</label>
<input id="lastName" type="text" class="form-control" :value="last" #input="emitChange(false, $event)">
</div>
</template>
<script>
export default {
props: ['value'],
methods: {
emitChange(isFirst, evt) {
let name = '';
let evtValue = evt.target.value == undefined ? "" : evt.target.value;
if (isFirst) {
name = evtValue +" "+ this.second;
} else {
name = this.first +" "+ evtValue;
}
this.value = name;
this.$emit('input', this.value);
}
},
computed: {
first() {
if (this.value != "")
return this.value.split(" ")[0];
else return "";
},
last() {
if (this.value != "")
return this.value.split(" ")[1];
else return "";
}
}
}
</script>
Which I also realize I'm messing up because I'm directly editing a prop value with:
this.value = name;
(not an error, but Vue.JS gives a warning).
However, even before that, typing in the first input box causes the second input box to update its value to undefined (...wat!?).
Would be grateful for advice on how to properly set up custom form control components! (and why this example isn't working).
I think, the problem here is you never know where the first name ends and where the last name starts. Take Barack Hussein Obama for instance and imagine he's Belgian, his name would be Barack Hussein van Obama. You can't safely assume which part ist first and which part is lastname.
However, if you could say the firstname is exactly one word and the rest is lastname, here's an example implementation (stripped down). To illustrate the problem, try to put in Obamas second name.
Otherwise, the component behaves like a two way bound component. You can alter the separate values on the fullname component, or edit the fullname on the root component and everything stays up to date. The watcher listens for changes from above, the update method emits changes back up.
Vue.component('fullname', {
template: '#fullname',
data() {
// Keep the separate names on the component
return {
firstname: this.value.split(' ')[0],
lastname: this.value.split(' ')[1],
}
},
props: ['value'],
methods: {
update() {
// Notify the parent of a change, chain together the name
// and emit
this.$emit('input', `${this.firstname} ${this.lastname}`);
},
},
mounted() {
// Parse the prop input and take the first word as firstname,
// the rest as lastname.
// The watcher ensures that the component stays up to date
// if the parent changes.
this.$watch('value', function (value){
var splitted = value.split(' ');
this.firstname = splitted[0];
splitted.shift();
this.lastname = splitted.join(' ');
});
}
});
new Vue({
el: '#app',
data: {
fullname: 'Barack Obama',
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.1.10/vue.js"></script>
<div id="app">
<fullname v-model="fullname"></fullname>
<p>Thanks, {{fullname}}</p>
<input v-model="fullname" />
</div>
<template id="fullname">
<div>
<input v-model="firstname" #input="update" type="text" id="firstname" />
<input v-model="lastname" #input="update" type="text" id="lastname" />
</div>
</template>
Using IronRouter, I have successfully rendered the page's template. I am trying to pass data from a collection to the unique page, but there is an error saying that the collection is not defined. Subscriptions aren't a problem since autopublish is installed.
I get the data from the form, store it, and then I want to display that data on the routed page.
So far, for the collection, I have:
import { Meteor } from 'meteor/meteor';
import { Template } from 'meteor/templating';
import { Works } from '../api/works.js';
import './work.js';
import './body.html';
Template.main.helpers({
works() {
return Works.find({}, { sort: { createdAt: -1 } });
},
});
Template.main.events({
'submit .new-work'(event) {
event.preventDefault();
const title = event.target.title.value;
const workBriefDesc = event.target.workBriefDesc.value;
const workFullDesc = event.target.workFullDesc.value;
const workId = this._id;
Works.insert({
title,
workBriefDesc,
workFullDesc,
createdAt: new Date(),
owner: Meteor.userId(),
username: Meteor.user().username,
workId,
});
event.target.title.value = '';
event.target.workbriefdesc.value = '';
event.target.workfulldesc.value = '';
},
});
Template.collab.helpers({
works: function(){
return Works.findOne({_id:Router.current().params.workId});
},
});
And for the IronRouter file:
Router.route('/works/:_id', function () {
this.render('Collab');
}, {
name: 'collab',
data: function(){
return Works.findOne({ _id: this.params._id});
},
});
And the template file:
<!-- Publishing the template work -->
<template name="main">
<form class="new-work col s12">
<div class="row">
<div class="input-field col s6">
<input id="title" type="text" class="validate">
<label for="title">Name of work</label>
</div>
<div class="input-field col s6">
<select>
<option value="" selected>Choose category</option>
<option value="1">Prose</option>
</select>
<label></label>
</div>
</div>
<div class="row">
<div class="input-field col s12">
<input id="workBriefDesc" type="text" length="250">
<label for="workBriefDesc">Brief description</label>
</div>
</div>
<div class="row">
<div class="input-field col s12">
<textarea id="workFullDesc" class="materialize-textarea" length="10000"></textarea>
<label for="workFullDesc">Full description</label>
</div>
</div>
<div class="row">
<div class="input-field col s12">
<textarea id="workessay" class="materialize-textarea"></textarea>
<label for="workessay">Essay</label>
</div>
</div>
<div class="modal-footer">
<button href="#!" class="modal-action modal-close waves-effect waves-grey btn-flat center" type="submit" name="action">Submit</button>
</div>
</form>
{{#each works}} {{ > work}} {{/each}}
</template>
<!-- Link to the unique page -->
<template name="work">
Go to work
</template>
<!-- Unique page attached to ID -->
<template name="collab">
{{title}} <br>
{{workBriefDesc}} <br>
{{workFullDesc}}
</template>
This is the error from the browser console:
Exception from Tracker recompute function:
meteor.js?hash=e3f53db…:930
ReferenceError: Works is not defined
at ctor.data (routes.js:17)
at Layout._data (iron_controller.js?hash=eb63ea9…:222)
at Layout.DynamicTemplate.data (iron_dynamic-template.js?hash=7644dc7…:215)
at iron_dynamic-template.js?hash=7644dc7…:248
at Blaze.View.<anonymous> (blaze.js?hash=983d07a…:2616)
at blaze.js?hash=983d07a…:1875
at Function.Template._withTemplateInstanceFunc (blaze.js?hash=983d07a…:3687)
at blaze.js?hash=983d07a…:1873
at Object.Blaze._withCurrentView (blaze.js?hash=983d07a…:2214)
at viewAutorun (blaze.js?hash=983d07a…:1872)
Added import { Works } from '/imports/api/works.js'; to my Router file.