Laravel/Vue.js issues - laravel

I need help with my code please. I can't figure it out. I'm getting a "TypeError: this.$http is undefined" and it's driving me insane. I trace it to $http, but I have no idea how to fix it. I've just finished my Laravel course, but Vue.js is new to me. Here's is my code:
<template>
<div class="container">
<div class="row">
<div class="col-md-8 col-md-offset-2">
<div class="panel panel-default">
<div class="panel-body">
<textarea rows="3" class="form-control" v-model="content"></textarea>
<br>
<button class="btn btn-success pull-right" :disabled="not_working" #click="create_post()">
Create a post
</button>
</div>
</div>
</div>
</div>
</div>
</template>
<script>
export default {
mounted() {
},
data() {
return {
content: '',
not_working: true
}
},
methods: {
create_post() {
this.$http.post('/create/post', { content: this.content })
.then((resp) => {
this.content = ''
noty({
type: 'success',
layout: 'bottomLeft',
text: 'Your post has been published !'
})
console.log(resp)
})
}
},
watch: {
content() {
if(this.content.length > 0)
this.not_working = false
else
this.not_working = true
}
}
}
</script>

I think you have a error in submitting the post request.
you need to learn about axios.
Try this example.
axios.post('/create/post', this.content).then((response) => {
// do something
})

npm install axios --save
Add Axios to your Vue.js project, you have to import it:
<script>
import axios from 'axios';
export default {
data() {
return {
posts: [],
errors: []
}
},
created() {
let payload={
content:this.content
}
axios.post('/create/post',payload)
.then(response => {
this.posts = response.data
})
.catch(e => {
this.errors.push(e)
})
}
}
</script>

Related

How get quill and other form to JS submit function?

I wanna use quill rich editor and other fields on my form. But cant get access to quill innerHTML from JS function. I am using Laravel with Alpinejs and my code is
<form x-data="contactForm()" #submit.prevent="submit">
<div class="col-12">
<div class="mt-2 w-100 bg-white" wire:ignore>
<div
x-data
x-ref="quillEditor"
x-init="
quill = new Quill($refs.quillEditor, {
theme: 'snow',
modules: {toolbar: '#toolbar'}
});
quill.on('text-change', function () {
$dispatch('input', quill.root.innerHTML);
});"
wire:model.debounce.2000ms="description"
class="sign__textarea"
style="height: 300px;"
>{{ old('description', $services_users->description) }}
</div>
</div>
</div>
<div class="col-12">
<input name="message" x-model="data.title">
</div>
<div class="col-12 col-xl-3 mt-5">
<button type="submit" x-text="buttonText" :disabled="loading"></button>
</div>
</form>
<script>
function contactForm() {
return {
data: {
title: "",
myQuill: quill.root.innerHTML,
},
buttonText: "Save",
loading: false,
submit() {
this.buttonText = "Saving...";
this.loading = true;
fetch('myurl.endpoint', {
method: "POST",
headers: {
"Content-Type": "application/json",
"Accept": "application/json",
},
body: JSON.stringify(this.data),
}).then(() => {
alert("Form submitted");
}).catch(() => {
alert("Something went wrong");
}).finally(() => {
this.data.title = ""
this.buttonText = "Save";
this.loading = false;
});
},
};
}
</scirpt>
Now i have an error Can't find variable: quill how can i get all fields from form and send to backend event if quill is not a form field?
It doesn't work because you're calling the variable "quill" in the parent and you're declaring it in the child. To fix it declare the x-init directive in the form.
listening to the "text-change" event is not necessary. A good option is to add the content of the container before submitting the form.
see : https://alpinejs.dev/directives/data#scope
<form x-data="contactForm()" x-init="
quill = new Quill($refs.quillEditor, {
theme: 'snow'
});
quill.on('text-change', function () {
$dispatch('input', quill.root.innerHTML);
});" #submit.prevent="submit">
<div class="col-12">
<div class="mt-2 w-100 bg-white" wire:ignore>
<div
x-ref="quillEditor"
wire:model.debounce.2000ms="description"
class="sign__textarea"
style="height: 300px;"
>{{ old('description', $services_users->description) }}
</div>
</div>
</div>
<div class="col-12">
<input name="message" x-model="data.title">
</div>
<div class="col-12 col-xl-3 mt-5">
<button type="submit" x-text="buttonText" :disabled="loading"></button>
</div>
</form>
<script>
function contactForm() {
return {
quill:null,
data: {
title: "",
// myQuill: function(){ return this.quill.root.innerHTML}
},
buttonText: "Save",
loading: false,
submit() {
this.buttonText = "Saving...";
//add content quill here
this.data.myQuill = this.quill.root.innerHTML;
this.loading = true;
fetch('myurl.endpoint', {
method: "POST",
headers: {
"Content-Type": "application/json",
"Accept": "application/json",
},
body: JSON.stringify(this.data),
}).then(() => {
alert("Form submitted");
}).catch(() => {
alert("Something went wrong");
}).finally(() => {
this.data.title = ""
this.buttonText = "Save";
this.loading = false;
});
},
};
}
</script>
Ok this is what i did
<form x-data="contactForm()" x-init="initQuill()" x-on:submit="submit()" method="POST" action="target.url">
<div x-ref="editor"></div>
<input x-ref="editorValue" type="hidden" name="hidden_input">
<button>Save</button>
</form>
<script>
function contactForm(){
return {
initQuill(){
new Quill(this.$refs. editor, {theme: 'snow'});
},
submit(){
console.log(this.$refs. editor.__quill.root.innerHTML);
this.$refs.editorValue.value = this.$refs.editor.__quill.root.innerHTML;
}
}
}
</script>
Now is ok and works with basic. You can extend function with new features etc. Thx for help guys.

[Vue warn]: Error in mounted hook: "Error: viewType "" is not available. Please make sure you've loaded all neccessary plugins

Im trying to use FullCalendar as a vue component in Laravel. I've loaded the plugins correctly as per the documentation but for whatever reason, they are not loading https://fullcalendar.io/docs/vue
Component:
template>
<div class="container">
<div class="row justify-contnet-center">
<div class="col-lg-8">
<form #submit.prevent>
<div class="form-group">
<label for="event_name">event Name</label>
<input
type="text"
id="event_name"
class="form-control"
v-model="newevent.event_name"
>
</div>
<div class="row">
<div class="cold-lg-8">
<div class="form-group">
<label for="date">Date</label>
<input
type="date"
id="date"
class="form-control"
v-model="newevent.date"
>
</div>
</div>
<div class="row">
<div class="col-lg-8">
<div class="form-group">
<label for="time">Time</label>
<input
type="time"
id="time"
class="form-control"
v-model="newevent.time"
>
</div>
</div>
</div>
</div>
<div class="col-lg-6 mb-4" v-if="addingMode">
<button class="btn btn-custom" #click="addNewevent">Book event</button>
</div>
<template>
<div class="col-lg-6 mb-4">
<button class="btn btn-success" #click="updateevent">Update</button>
<button class="btn btn-danger" #click="deleteevent">Delete</button>
<button class="btn btn-warning" #click="addingMode = !addingMode">Cancel</button>
</div>
</template>
</form>
</div>
<div class="col-lg-8 full-calendar" id="calendar">
<FullCalendar #eventClick="showevent" defaultView:="dayGridMonth" :plugins="calendarPlugins" :events="events"/>
</div>
</div>
</div>
</template>
<script>
import { Calendar } from '#fullcalendar/core'
import FullCalendar from '#fullcalendar/vue'
import dayGridPlugin from '#fullcalendar/daygrid'
import interactionPlugin from '#fullcalendar/interaction'
import axios from 'axios'
export default {
components:{
FullCalendar // make custom tag avaliable
},
data() {
return {
calendarPlugins: [ dayGridPlugin, interactionPlugin],
events: "",
newevent: {
event_name: "",
date: "",
time: ""
},
addingMode: true,
indexToUpdate: ""
};
},
created() {
this.getevents();
},
methods: {
addNewevent() {
axios.post('/api/event', {
...this.newevent
})
.then(data=> {
this.getevents(); //update list of getevents
this.resetForm();
})
.catch(err =>
// alert("Unable to add event")
console.log(err.response.data)
);
},
showevent(arg) {
console.logt(arg);
this.addingMode = false;
const {id, event, date, time} = this.events.find (
event => event.id === +arg.event.id
);
this.indexToUpdate = id;
this.newevent = {
event_name: event, // comeback to and see if inserts into db as event_name
date: date,
time: time
};
},
updateevent() {
axios.put('/app/event/' + this.indexToUpdate, {
...this.newevent
})
.then(resp => {
this.resetForm();
this.getevents();
this.addingMode = !this.addingMode;
})
.catch(err =>
// alert('Unable to update event!')
console.log(err.response.data)
);
},
deleteevent() {
axios.delete('/api/event/' + this.indexToUpdate)
.then(resp => {
this.resetForm();
this.getevents();
this.addingMode = !this.addingMode;
})
.catch(err =>
// alert('Unable to delete event')
console.log(err.response.data)
);
},
getevents(){
axios.get('/api/event')
.then(resp => (this.events = resp.data.data))
.catch(err => console.log(err.response.data));
},
resetForm() {
Object.keys(this.newevent).forEach(key=> {
return (this.newevent[key] = "");
});
}
},
watch: {
indexToUpdate() {
return this.indexToUpdate
}
}
};
Then also I have initialized the component with es6 as per this part of the doc https://fullcalendar.io/docs/initialize-es6
import { Calendar } from '#fullcalendar/core';
import dayGridPlugin from '#fullcalendar/daygrid';
import interactionPlugin from '#fullcalendar/interaction';
document.addEventListener('DOMContentLoaded', function() {
let calendarEl = document.getElementById('calendar');
let calendar = new Calendar(calendarEl, {
plugins: [ dayGridPlugin , interactionPlugin ]
});
calendar.render();
});
This is my app.js
Vue.component('calendar-component', require('./components/CalendarComponent.vue').default);
<FullCalendar #eventClick="showevent" defaultView:="dayGridMonth" :plugins="calendarPlugins" :events="events"/>
should become
<FullCalendar :options="calendarOptions" />
I saw the FullCalendar code in github and it doesn't support props defaultView and plugins. Instead it uses prop with name "options"
<script>
import FullCalendar from '#fullcalendar/vue'
import dayGridPlugin from '#fullcalendar/daygrid'
import interactionPlugin from '#fullcalendar/interaction'
export default {
components: {
FullCalendar // make the <FullCalendar> tag available
},
data() {
return {
calendarOptions: {
plugins: [ dayGridPlugin, interactionPlugin ],
initialView: 'dayGridMonth'
}
}
}
}
</script>
<template>
<FullCalendar :options="calendarOptions" />
</template>
Please check the plugin documentation

Property or method "contact" is not defined on the instance but referenced during render Vuejs Laravel

I'm developing chat app on laravel using vue.js and i'm new to vue.js.
but i'm getting below mentioned error, please help me solve this
Error1 :
[Vue warn]: Property or method "contact" 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
Error2 :
[Vue warn]: Error in render: "TypeError: Cannot read property 'avatar' of undefined"
/ ChatApp.vue file/
<template>
<div class="chat-app">
<Conversation :contact="selectedContact" :messages="messages"/>
<ContactsList :contacts="contacts"/>
</div>
</template>
<script>
import Conversation from './Conversation.vue';
import ContactsList from './ContactsList.vue';
export default {
props: {
user: {
type: Object,
required: true
}
},
data(){
return {
selectedContact: null,
messages: [],
contacts: []
};
},
mounted(){
axios.get('/contacts')
.then((response) => {
this.contacts = response.data;
});
},
methods: {
startConversationWith(contact) {
axios.get(`/conversation/$(contact.id)`)
.then((response) => {
this.messages = response.data;
this.selectedContact = contact;
})
}
},
components: { ContactsList, Conversation }
};
</script>
/ ContactsList.vue file/
<template>
<div class="contacts-list">
<ul v-if="contacts.length > 0">
<li v-for:"(contact, index) In contacts" :key="contact.id"
#click="selectContact(index, contact)" :class="{ 'selected' : index ==
selected}">
<div class="avatar">
<img :src="contact.avatar" :alt="contact.name">
</div>
<div class="contact">
<p class="name">{{ contact.name }}</p>
<p class="email">{{ contact.email }}</p>
</div>
</li>
</ul>
</div>
</template>
<script>
export default {
props: {
contacts: {
type: Array,
default: []
}
},
data() {
return {
selected: 0
};
},
methods: {
selectContact(index, contact) {
this.selected = index;
this.$emit('selected', contact);
}
}
};
</script>
/ conversation.vue /
<template>
<div class="conversation">
<h1>{{ contact ? contact.name : 'Select a contact' }}</h1>
<MessagesFeed :contact="contact" :messages="messages" />
<MessageComposer #send="sendMessage" />
</div>
</template>
<script>
import MessagesFeed from './MessagesFeed.vue';
import MessageComposer from './MessageComposer.vue';
export default {
props: {
contact: {
type: Object,
default: null
},
messages: {
type: Array,
default: []
}
},
methods:{
sendMessage(text) {
console.log(text);
}
},
components: {MessagesFeed, MessageComposer}
};
</script>
#Akash you can use it this way :
data() {
return {
contactsNotEmpty:false
}
},
// ...
mounted() {
axios.get('/contacts')
.then((response) => {
this.contacts = response.data;
this.contactsNotEmpty = true;
});
}
<ul v-if="contactsNotEmpty">
...
</ul>
also you may check this vuejs article about what is happening : https://vuejs.org/2016/02/06/common-gotchas/#Why-isn%E2%80%99t-the-DOM-updating
I guess you can do it like that:
<ul v-if="contacts.length > 0">
<li v-for="contact in contacts" :key="contact.id">
<div class="avatar">
<img :src="contact.avatar" :alt="contact.name">
</div>
<div class="contact">
<p class="name">{{ contact.name }}</p>
<p class="email">{{ contact.email }}</p>
</div>
</li>
</ul>
The first error is throwing in your Conversation.vue, you were passing data to a child component, you have to make sure it is defined as a prop in that component
export default{
props: ['contact']
};
and if it is defined, your prop type is not expecting a null value. I would change it to string and on rendering in my ChatApp.vue, I would set selectedContact to string.Empty||''
For the second error, the avatar key is missing from your response object. You have to check if it is present first before accessing it. Kindly refer to El Alami Anas's answer above.

Passing parameter from axios to laravel

In my application I'm working with comment, each product has its own comment.Comment in MySql contains column 'computer_comment' with foreign key(id).When I send 'computer_comment' from axios to laravel comments doesn't shown, I guess that 'computer_comment' is null or undefined.
I tried to send 1 or 2 instead 'computer_comment', in this case it works.
CommentComponent.vue
<template>
<div>
<div v-for="l in list">
<div v-if="l.computer_comment==current">
<div class="card" >
<div class="card body" >
<h4 style="text-decoration: underline">{{l.name}}</h4>
<p >{{l.body}}</p>
</div>
</div>
<br>
</div>
</div>
</div>
</template>
<script>
export default{
props: ['message'],
data(){
return{
list: [],
comment:{
id: '',
user_comment: '',
computer_comment: '',
name: '',
body: ''
},
current: this.message
}
},
created() {
this.show_comment();
},
methods: {
show_comment(){
axios.get('/current_comment').then(result => {
this.list = result.data;
console.log(result.data);
});
},
removeCom(id){
axios.post('/remove/'+id).then(result => {
this.show_comment();
}).catch(err => {
console.log(err);
});
}
},
}
</script>
info.blade.php
<div id="info">
<comment message="{{$computer->id}}"></comment>
.....
</div>

Vue Object is Empty

I'm using Vuejs to display data from an API to a template. I'm trying to figure out why I am not returning data for the team so I can display in for the template. Right now when I use the VueJS Chrome Extention it shows that the team is an empty object.
<div v-if="team">
<div class="row">
<div class="col-12 col-sm-12">
<div class="fw-700 pb3 mb5" style="border-bottom: 1px solid #333;">Name:</div>
<div class="mb10" style="font-size: 20px;">{{ team.name }}</div>
</div>
</div>
<script>
module.exports = {
http: {
headers: {
'X-CSRF-TOKEN': window.Laravel.csrfToken
}
},
props: [ 'id', 'editable' ],
data: function(){
return {
modalName: 'additionalInfo',
team:{
}
}
};
},
methods: {
fetchInfo: function(){
this.$http.get('/api/teams/info', { params: { id: this.id } }).then((response) => {
this.team = response.data;
});
},
},
}
}
</script>
It is empty because your method fetchInfo isn't being called, so you need to do something like this:
created () {
this.fetchInfo()
}
This will call the function fetchInfo which in turn will fetch and fill this.team

Resources