Showing data after hard refresh - laravel

im working with vue & laravel.i have a edit profile page with some forms in it(name,email,...)
the default value of this form not showing for the first time, but if user refresh the page everything will be work!!!
<template>
<label>Name:</label>
<input type="text" v-model="name">
<label>Email:</label>
<input type="email" v-model="email">
<template>
<script>
export default {
data () {
return {
name:'',
email:'',
}
},
mounted : function(){
this.getVueItems();
},
methods: {
getVueItems: function(){
axios.get('./api/auth/me').then(response => {
var vm = this;
vm.name = response.data.name;
vm.email = response.data.email;
});
},
getAuthUser () {
this.user = this.$store.getters.currentUser
},
updateAuthUser () {
this.submiting = true,
axios.put('./api/auth/update', {
name:this.name,
email:this.email,
})
.then(response => {
// this.submiting = false;
location.reload(true);
// success();
})
.catch(error => {
this.submiting = false;
})
},
}
}
</script>
whats is the problem?

As you are using arrow function this keyword is already accessible inside the function.
And for this you should first check in console if you are getting proper response value from api in console.
Hence change your function as below and check once.
async getVueItems() {
await axios.get('./api/auth/me').then(response => {
console.log(response);
this.name = response.data.name;
this.email = response.data.email;
});

Related

Vue Form component in Laravel getting 422 error on submission

I am trying to add a Vue form component to my Laravel application so I can reuse it in a few places throughout the app. But when I submit the form I get a 422 error saying that the route is not found.
Form component:
<template>
<form #submit.prevent="mail" method="POST">
</form>
</template>
<script>
import FormMixin from '../FormMixin';
export default {
mixins: [ FormMixin ],
data() {
return {
'action': 'submit',
}
}
}
</script>
Form Mixin
export default {
data() {
return {
fields: {},
errors: {},
success: false,
loaded: true,
action: '',
}
},
methods: {
mail() {
if (this.loaded) {
this.loaded = false;
this.success = false;
this.errors = {};
axios.post(this.action, this.fields).then(response => {
this.fields = {}; //Clear input fields.
this.loaded = true;
this.success = true;
}).catch(error => {
this.loaded = true;
if (error.response.status === 422) {
this.errors = error.response.data.errors || {};
}
});
}
},
},
}
Controller
public function mail(NewConctactRequest $contact) {
Mail::to('example#example.com')->send(new NewContact($contact));
return redirect()->route('thank you');
return response()->json(null, 200);
}
Web Routes
Route::get('/home', 'HomeController#index')->name('home');
Route::get('adventures', 'PageController#adventures')->name('adventures');
Route::get('crew', 'PageController#crew')->name('crew');
Route::get('events', 'PageController#events')->name('events');
Route::get('gallery', 'PageController#gallery')->name('gallery');
Route::get('thank_you', 'PageController#thank_you')->name('thank you');
Route::get('contact', 'ContactController#show')->name('contact');
Route::post('submit', 'ContactController#mail')->name('mail contact');
I have Axios installed already and the CSRF token is set in the head pf the document. When I use the form as just a standard form (not using Vue) it submits properly.

Upload file with Vuejs

i'm working in Laravel. i need to upload file with Vuejs. but it's not working. I add this code:
Blade (File upload):
<input class="form-control" type="file" >
Script Vuejs :
var app = new Vue({
el: '#app',
data: {
person: {
id: 0,
user_name:'',
position_id:'',
image:'',
},
},
methods: {
addPerson: function () {
axios.post('/addperson', this.person)
.then(response => {
console.log(response.data);
if (response.data.etat) {
this.person = {
id: 0,
user_name: response.data.etat.user_name,
position_name: response.data.etat.position_id,
image: response.data.etat.image
};
}
})
.catch(error => {
console.log('errors: ', error)
})
},
Controller:
public function addPerson(Request $request){
$person = new Person;
$person->user_name=$request->user_name;
$person->position_id=$request->position_id;
if($request->hasFile('photo')){
$person->image= $request->image->store('image');
}
$person->save();
return back()->with('success', 'New Position added successfully.');
My Axios post function is working without the image upload line code. I just don't know how to add the upload code.
Thank you if someone can help.
In your blade file
<input type="file" #change="onFileChange" name="id_image" id="id_image" class="inputFile">
In your vue.js file, under methods:
onFileChange(e) {
let files = e.target.files || e.dataTransfer.files;
if (!files.length)
return;
this.createImage(files[0]);
},
createImage(file) {
let reader = new FileReader();
reader.onload = (e) => {
this.person.image = e.target.result;
};
reader.readAsDataURL(file);
},
That should allow your axios code to upload the image. Note, that it uploads in base64, so if you need validators you will have to create a custom Validator for base64 images.
I struggled to find out how to do this, but I've now found a way. Hopefully this makes someones life easier(I have the uploadUserImage method in a mixin):
HTML:
<input type="file" #change="uploadImage($event)">
JS:
uploadImage (e) {
this.file = e.currentTarget.files[0]
let formData = new FormData()
formData.append('img', this.file)
this.uploadUserImage(formData)
}
uploadUserImage: function (formData) {
axios.post('http://snowdon-backend.local:8000/api/users/img', formData,
{
headers: {
'Content-Type': 'multipart/form-data'
}
})
.then(function (response) {
console.log(response)
})
}
Make sure file is set in the data method as well:
data () {
return {
file: ''
}
}

live search input

I'm creating a live search input in ionic 3
inside a form group
inside my ts file, I'm using
getsubelements(selectedValue) {
if(selectedValue){
this.VisitesProvider.getEcolesLive(selectedValue).then((result) =>{
this.responseData = result;
});
}
}
and my provider look like :
getEcolesLive(query){
var data = {
"q" :query
}
return new Promise((resolve, reject) =>{
let headers = new HttpHeaders();
this.http.post(ecoleliveurl, JSON.stringify(data), {headers: headers}).
subscribe(res =>{
resolve(res);
console.log(res);
}, (err) =>{
reject(err);
});
});
}
I'm getting the expected result in json format from mu api server:
[{"name":"Ecole EC","id":"22"}]
I want to populate the names in a dropdown list and on click on the desired one of should replace the search input.
You can create a dropdown menu in the component template like this.
<select [ngModel]="selectedItem" (ngModelChange)="onChange($event)" name="sel2">
<option [value]="i" *ngFor="let i of responseData">{{i.name}}</option>
</select>
In your component.
onChange(newValue) {
console.log(newValue);
this.selectedItem = newValue;
}
this is the html
<ion-item>
<ion-label>Ecole</ion-label>
<ion-input type="text" placeholder="Search" formControlName="ecole" (ionChange)="getsubelements($event._value)" ng-focus="focus=true"></ion-input>
</ion-item>
<div id="search-results" ng-show="focus">
<div class="search-result" *ngFor="let i of responseData" (click)="onChange(i.name)">{{i.name}}</div>
</div>
this is the js part
the form groupe :
visitData = {"name":"", "startdate":"","linkedto":"","ecole":"","selectedItem":""};
constructor(public navCtrl: NavController, public navParams: NavParams,private formBuilder: FormBuilder,public VisitesProvider:VisitesProvider) {
this.visiteFormGroup = this.formBuilder.group({
name: ['', Validators.required],
startdate: ['', Validators.required],
ecole:['', Validators.required],
});
}
the two functions :
getsubelements(selectedValue) {
if(selectedValue){
this.VisitesProvider.getEcolesLive(selectedValue).then((result) =>{
this.responseData = result;
var x = document.getElementById("search-results");
x.style.display="block"
});
}
}
onChange(newValue) {
console.log("called")
console.log(newValue.name)
this.visiteFormGroup.controls["ecole"].setValue(newValue);
var x = document.getElementById("search-results");
x.style.display="none"
}
and the provider function
getEcolesLive(query){
var data = {
"q" :query
}
return new Promise((resolve, reject) =>{
let headers = new HttpHeaders();
this.http.post(ecoleliveurl, JSON.stringify(data), {headers: headers}).
subscribe(res =>{
resolve(res);
console.log(res);
}, (err) =>{
reject(err);
});
});
}
i hope it will help somone :)

My textarea input is not be empty after send message using Vue

I am using laravel and Vue. I have created a messenger application. Everything is done. But I am facing a problem. That is, after press enter button, message goes to the desired person. But the message still be available in the input filed until I refresh the page.
Here is my html code.
<input type="hidden" v-model="conID">
<textarea class="col-md-12 form-control" v-model="msgFrom" #keydown="inputHandler"
style="margin-top: 15px;border: none; resize: none;"></textarea>
Here is my Vue code.
inputHandler(e){
if(e.keyCode === 13 && !e.shiftkey){
e.preventDefault();
this.sendMsg();
}
},
sendMsg()
{
if(this.msgFrom){
axios.post('http://localhost:8000/sendMessage',{
conID:this.conID,
msg:this.msgFrom
})
.then(function(response){
console.log(response.data);
if(response.status===200){
app.singleMsgs = response.data;
}
})
.catch(function (error){
console.log(error);
});
}
Can anyone please help me. Just how I can make textarea empty after sending a message.
Thank's in advance.
should be as easy as clearing it once the message is sent
clear the form with: this.msgFrom = '', because you're doing it within a promise function (and without an arrow function), you need to store the this scope and pass it; usually done using var self = this
example:
inputHandler(e) {
if (e.keyCode === 13 && !e.shiftkey) {
e.preventDefault();
this.sendMsg();
}
},
sendMsg() {
var self = this; // <--- store scope 'this'
if (this.msgFrom) {
axios.post('http://localhost:8000/sendMessage', {
conID: this.conID,
msg: this.msgFrom
})
.then(function(response) {
console.log(response.data);
if (response.status === 200) {
app.singleMsgs = response.data;
self.msgFrom = ''; // <--- and then clear form
}
})
.catch(function(error) {
console.log(error);
});
}
}

wait for a job finished to render component in vuejs

I have a component here, and I need first to make a request using socket.io :
<template>
<h1>Don't show me before the socket's response</h1>
</template>
<script>
export default {
beforeCreate: function() {
let sessid = this.$cookie.get('sessid')
this.$options.sockets.logout = (data) => {
if (data.redirect) {
this.$router.push(data.redirect)
} else {
console.log('here, you can render the template')
}
}
this.$socket.emit('logout', { sessid })
}
}
</script>
This code works, but it shows the template in browser for a quick moment, before the redirection happens.
I would like to know if there's a tick to wait the socket response for rendering the template.
You can use v-if, when the socket response arrives, you can set a variable which can be used with v-if to not show the HTML, something like following:
<template>
<h1 v-if="sockResp">Don't show me before the socket's response</h1>
</template>
<script>
export default {
data: function() {
return {
sockResp: false
}
},
beforeCreate: function() {
let sessid = this.$cookie.get('sessid')
this.$options.sockets.logout = (data) => {
if (data.redirect) {
this.$router.push(data.redirect)
} else {
console.log('here, you can render the template')
this.sockResp = true
}
}
this.$socket.emit('logout', { sessid })
}
}
</script>

Resources