Why does Vue evaluate my v-if to false despite it being true? - laravel

When I run this, vue returns the second template, even though groups.length is equal to 1.
Why? Does it have to do with the order in which the mounting occurs and v-if is evaluated? Again, I am certain that groups.length evaluates to 1. I have tried using beforeMount as opposed to mounted, but that did not work.
<template v-if = "groups.length">
<ul id = "groupList">
<li v-for = "group in groups">
<a>{{ group.name }}</a>
</li>
<div class = "addSidebar">
<label class = "btn" for = "modal-1">+</label>
</div>
</ul>
</template>
<template v-else>
<ul id = "groupList">
<li>
<a>You have not created/joined any groups.</a>
</li>
<div class = "addSidebar">
<label class = "btn" for = "modal-1">+</label>
</div>
</ul>
</template>
<script>
export default {
data() {
return {
groups: {}
}
},
methods: {
getGroups() {
axios.get('groupList').then((response) => {
this.groups = response.data
}).catch((errors) => {
console.log(errors)
});
},
newModal() {
$('#modal').modal('show');
}
},
mounted() {
this.getGroups()
},
name: "groupList"
}
</script>

you need to use javascript Async
https://www.w3schools.com/js/js_async.asp
<template >
<div>
<ul id="groupList" v-if="groups.length">
<li v-for="group in groups" :key="group.id">
<a>{{ group.name }}</a>
</li>
<div class="addSidebar">
<label class="btn" for="modal-1">+</label>
</div>
</ul>
<ul id="groupList" v-else>
<li>
<a>You have not created/joined any groups.</a>
</li>
<div class="addSidebar">
<label class="btn" for="modal-1">+</label>
</div>
</ul>
</div>
</template>
<script>
export default {
data() {
return {
groups: {},
};
},
methods: {
async getGroups() {
await axios
.get("groupList")
.then((response) => {
this.groups = response.data;
})
.catch((errors) => {
console.log(errors);
});
},
newModal() {
$("#modal").modal("show");
},
},
async mounted() {
await this.getGroups();
},
name: "groupList",
};
</script>
in your code you created 2 <template > which is not valid syntax and vue should have root element
https://v2.vuejs.org/v2/guide/components.html#A-Single-Root-Element

Change
v-if = "groups.length"
to:
v-if="groups && groups.length > 0"
And you should have a single that contains one elements in it.

Related

Inertia mounted hook with search resets pagination on every action

My vue file:
data() {
return {
search: '',
}
},
mounted() {
this.search = this.filters.search ?? '';
},
watch: {
search(value) {
Inertia.get('/contacts', { search: value }, {
preserveState: true,
replace: true,
})
}
The Laravel Controller:
$contacts = Model::query()
->paginate(10)
->withQueryString();
return Inertia::render('Contacts/List', [
'contacts' => $contacts,
'filters' => request()->only(['search']),
'currentPage' => request()->page,
]);
It all works perfectly if the mounted block is missing.
With it, on every Inertia reload a "new search" is registered (since it's changed in the mounted hook) and it returns to page 1, so basically, every time you change the page it returns you to page 1.
It should be working perfectly with the Composition API's setup, but not sure why can't I get it to work here.
I use axios instead of Inertia.js in pagination
<template>
<div class="row mt-4">
<div class="col-md-5">
<span
>showing {{ data.from }}-{{ data.to }} of
{{ data.total }} items</span
>
</div>
<div class="col-lg-7">
<nav aria-label="...">
<ul class="pagination float-end">
<template v-for="link in data.links" :key="link.id">
<li v-if="!link.url" class="page-item">
<a #click.prevent="paginate(link.label)" class="page-link">
<span
aria-hidden="true"
v-html="link.label"
></span>
</a>
</li>
<li
v-else
:class="{ active: link.active }"
class="page-item"
>
<a
#click.prevent="paginate(link.label)"
v-html="link.label"
class="page-link"
></a>
</li>
</template>
</ul>
</nav>
</div>
</div>
</template>
<script>
import axios from 'axios'
export default {
props: ["data", "url"],
methods: {
paginate(label) {
console.log(`${route(this.url)}?page=${label}`);
axios.get(`${route(this.url)}?page=${label}`).then((res) => {
this.$emit('paginate', res.data)
});
}
}
}
</script>
I ran into the same issue, and after some digging I found this answer. The gist is that you should set your search parameter directly in the data attribute instead of using mounted():
data() {
return {
search: this.filters.search ?? '',
}
},
watch: {
search(value) {
Inertia.get('/contacts', { search: value }, {
preserveState: true,
replace: true,
})
}

Active user does not show in real time chat app

I am following up this guide https://www.codechief.org/article/real-time-chat-app-with-laravel-6-vue-js-and-pusher#gsc.tab=0 to create real-time chat app in Laravel and Vue.
But it does not show list of active user.
Also this span never shows
<span class="text-muted" v-if="activeUser" >{{ activeUser.first_name }}` is typing...</span>
Also, this method does not work properly because in console log it shows undefined is typing...
sendTypingEvent() {
Echo.join('chat')
.whisper('typing', this.user);
console.log(this.user.fist_name + ' is typing now')
}
And it is not actually real time, because I see new messages only if I reload page.
This is Vue component
<template>
<div class="row">
<div class="col-8">
<div class="card card-default">
<div class="card-header">Messages</div>
<div class="card-body p-0">
<ul class="list-unstyled" style="height:300px; overflow-y:scroll" v-chat-scroll>
<li class="p-2" v-for="(message, index) in messages" :key="index" >
<strong>{{ message.user.first_name }}</strong>
{{ message.message }}
</li>
</ul>
</div>
<input
#keydown="sendTypingEvent"
#keyup.enter="sendMessage"
v-model="newMessage"
type="text"
name="message"
placeholder="Enter your message..."
class="form-control">
</div>
<span class="text-muted" v-if="activeUser" >{{ activeUser.first_name }} is typing...</span>
</div>
<div class="col-4">
<div class="card card-default">
<div class="card-header">Active Users</div>
<div class="card-body">
<ul>
<li class="py-2" v-for="(user, index) in users" :key="index">
{{ user.first_name }}
</li>
</ul>
</div>
</div>
</div>
</div>
</template>
<script>
export default {
props:['user'],
data() {
return {
messages: [],
newMessage: '',
users:[],
activeUser: false,
typingTimer: false,
}
},
created() {
this.fetchMessages();
Echo.join('chat')
.here(user => {
this.users = user;
})
.joining(user => {
this.users.push(user);
})
.leaving(user => {
this.users = this.users.filter(u => u.id != user.id);
})
.listen('ChatEvent',(event) => {
this.messages.push(event.chat);
})
.listenForWhisper('typing', user => {
this.activeUser = user;
if(this.typingTimer) {
clearTimeout(this.typingTimer);
}
this.typingTimer = setTimeout(() => {
this.activeUser = false;
}, 1000);
})
},
methods: {
fetchMessages() {
axios.get('messages').then(response => {
this.messages = response.data;
})
},
sendMessage() {
this.messages.push({
user: this.user,
message: this.newMessage
});
axios.post('messages', {message: this.newMessage});
this.newMessage = '';
},
sendTypingEvent() {
Echo.join('chat')
.whisper('typing', this.user);
console.log(this.user.fist_name + ' is typing now')
}
}
}
</script>
"Also, this method does not work properly because in console log it shows undefined is typing..."
i assume you made a typo in your console.log, you probably meant:
this.user.first_name
Concerning your "realtime" problem, i suspect it might be because your broadcasted Event is being queued, so you might want to use the ShouldBroadcastNow instead of ShouldBroadcast

How to use the selection from my vue component in my blade file

I have build a vue-component which takes a list of objects and two criteria lists as props. The select lists are passed to two select inputs in the template. When either one is changed the list is filtered using the selected criteria. How do I get access to this filtered list in my blade file?
Here is my code.
Blade file:
<subjecttable-select :data-subjecttable="{{$subjectslessons->toJson()}}"
:data-departments="{{$departments->toJson()}}"
:data-subjects="{{$subjects->toJson()}}" #input="selectedsubjects">
</subjecttable-select>
#{{selectedsubjects}}
Vue-component
<template>
<div >
<div class="row mb-2 mx-2">
<form class="form-inline justify-content-between" >
<div class="form-group row mb-1">
<label class="col-auto col-form-label text-md-left" for="department">Leerjaar</label>
<div class="col-auto">
<select id= "department" class="form-control form-control-sm custom-select" v-model="department" #change="select()">
<option v-for="department_item in dataDepartments" :value="department_item['id']">
{{department_item["name"]}}
</option>
</select>
</div>
</div>
<div class="form-group row">
<label class="col-auto col-form-label text-md-leftt" for="subject">Vak</label>
<div class="col-auto">
<select id="subject" class="form-control form-control-sm custom-select" v-model="subject" #change="select()">
<option v-for="subject_item in dataSubjects" :value="subject_item['id']">
{{subject_item["description"]}}
</option>
</select>
</div>
</div>
<button class="btn-outline-primary" #click="reset()">Reset</button>
</form>
</div>
</div>
</template>
<script>
export default {
name:"subjecttable-select",
props: {
dataDepartments: { type: Array, required: true },
dataSubjects:{ type: Array, required: true},
dataSubjecttable: {type: Array, required: true },
value:{},
},
data() {
return {
selected:this.dataSubjecttable,
subject:"",
department:"",
}
},
methods:{
select(){
var item;
console.log(this.subject);
this.selected=[];
for(item of this.dataSubjecttable){
if(//get the subbejctlessons who are in the selected department
(this.department==="" || item["department_id"]===this.department) &&
//whose subject is the selected subject
(this.subject===""|| item["subject_id"]===this.subject)
){
this.selected.push(item);
}
}
this.$emit('input',this.selected);
},
reset(){
this.value = this.dataSubjecttable;
this.subject = "";
this.department="";
},
},
created(){
this.select();
},
filters: {
dateFilter(value){
var isDate = !isNaN(Date.parse(value));
if (isDate ){
var dateValue=new Date(value);
return dateValue.toLocaleDateString();
}
else{
return value;
}
}
},
};
</script>
app.js
Vue.component('subjecttable-select', require('./components/SubjectSelection.vue').default);
/**
* Next, we will create a fresh Vue application instance and attach it to
* the page. Then, you may begin adding components to this application
* or customize the JavaScript scaffolding to fit your unique needs.
*/
const app = new Vue({
el: '#app',
});
As you can see I emit an input event in my component but I have trouble accessing the value in the blade file.
Ideally, I think you want to do is load your SelecttableSelect component within another parent Vue component. This will allow you to trickle your events down to the parent component and use the data much more easily.
I have not tested this, but it's along the lines of what I would do to get started. You would need to format the output to your needs.
Lessons.vue
<template>
<div>
<!-- YOUR SELECT IS NOW DEFINED HERE, NOT IN THE BLADE FILE -->
<!-- Select -->
<subjecttable-select :data-subjecttable="dataSubjecttable"
:data-departments="dataDepartments"
:data-subjects="dataSubjects"
#input="updateResults"
>
</subjecttable-select>
<!-- End Select -->
<!-- Department -->
<div>
<h1>Department</h1>
<div v-if="results.department_id > 0">
<ul>
<li v-for="(value, index) in findElementById(dataDepartments, results.department_id)">
{{ index }} : {{ value }}
</li>
</ul>
</div>
</div>
<!-- End Department -->
<!-- Subject -->
<div>
<h1>Subject</h1>
<div v-if="results.subject_id > 0">
<ul>
<li v-for="(value, index) in findElementById(dataSubjects, results.subject_id)">
{{ index }} : {{ value }}
</li>
</ul>
</div>
</div>
<!-- End Subject -->
</div>
</template>
<script>
// import your select component
import SubjecttableSelect from './SubjecttableSelect';
export default {
components: {
// register the component
SubjecttableSelect,
},
props: {
dataDepartments: { type: Array, required: true },
dataSubjects:{ type: Array, required: true},
dataSubjecttable: {type: Array, required: true },
},
name: "Lessons",
data() {
return {
results: {
subject_id: 0,
department_id: 0,
},
}
},
methods: {
updateResults(data) {
this.results = data;
},
findElementById(element, id) {
return element.find(el => el.id === id);
}
},
}
</script>
<style scoped>
</style>
app.js
// register the new component
Vue.component('lessons', require('./components/Lessons.vue').default);
// subjecttable-select can now be imported within lessons
const app = new Vue({
el: '#app',
});
your.blade.php (please note the single quotes)
<lessons :data-subjecttable='#json($subjectslessons)'
:data-departments='#json($departments)'
:data-subjects='#json($subjects)'>
</lessons>

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.

Display content from AJAX request using setState

I'm doing a webapp using github search API. I want the info for each repo to be displayed under the specific repo.
I want the content from the AJAX request to be displayed when the specific button is being pressed. I am using React. Since I'm using item.x to access the information I need to get that item and I assume I need to use map but when doing that it will display all the results and not just the specific repository's. Anyway that I can get the Item since it currently says it's undefined?
let searchTerm;
class SearchBox extends React.Component {
constructor(props) {
super(props);
this.onClick = this.onClick.bind(this);
this.state = { repositories: [],
showInfo: false };
}
render() {
let moreDetail;
if(this.state.showInfo){
moreDetail= <div className="info"> <li>
<p>Open issue count </p>:{item.open_issues_count}
</li>
<li>
<p>Number of forks </p>:{item.forks}
</li>
<li>
<p>Language </p>:{item.language}
</li></div>;
}
return(
<div>
<form>
<input type="text" className="searchbox" ref={(input) => { this.searchBox = input; }}/>
<button onClick={this.onClick}>Search</button>
</form>
<h2>Repositories</h2>
<ul>
{ this.state.repositories.map( ( item, index ) => (
<div key={ index }>
<a href={item.html_url}> <li >
{ item.name }
</li>
</a>
{moreDetail}
<button onClick={this._handleClick.bind(this)}>Detailed view</button>
</div>
)) }
</ul>
</div>
);
}
_handleClick(){
this.setState({
showInfo: !this.state.showInfo
});
}
onClick(event) {
searchTerm = this.searchBox.value;
let endpoint = 'https://api.github.com/search/repositories?sort=stars&order=desc&q=' + searchTerm;
console.log(searchTerm);
fetch(endpoint)
.then(blob => blob.json())
.then(response => {
this.setState({ repositories: response.items });
});
event.preventDefault();
}
}
The problem is with context. When you define the moreDetail variable, you don't have item in your context (only during the map function you have that.)
One option is to use the variable moreDetail as a function that receives the item you want to show.
Your render method should look something like:
render() {
const moreDetail = (item) => ( !this.state.showInfo ? <span /> :
<div className="info">
<li>
<p>Open issue count </p>:{item.open_issues_count}
</li>
<li>
<p>Number of forks </p>:{item.forks}
</li>
<li>
<p>Language </p>:{item.language}
</li>
</div>
);
return (
<div>
<form>
<input type="text" className="searchbox" ref={(input) => { this.searchBox = input; }}/>
<button onClick={this.onClick}>Search</button>
</form>
<h2>Repositories</h2>
<ul>
{ this.state.repositories.map( ( item, index ) => (
<div key={ index }>
<a href={item.html_url}> <li >
{ item.name }
</li>
</a>
{moreDetail(item)}
<button onClick={this._handleClick.bind(this)}>Detailed view</button>
</div>
)) }
</ul>
</div>
);
}

Resources