VueJS: Using A Loading Icon When Waiting For Results Of Asynchronous Database Calls - vue.js

I wonder where and how to setup a loading icon in VueJS, when the data my site depends on, isn't ready.
Do you know how to do this?
Would be nice and helpful.

Considering you are using axios which is currently the most used http client for vue.js you would do something like
data: function() {
return { results: [], loading: true};
}
And now let's say you load on create
created: function() {
axios.get('/path/to/my/data/endpoint')
.then(function(response) {
this.result = response.data;
this.loading = false;
}.bind(this))
.catch(function() {
this.loading = false;
}.bind(this));
}
And in your template you have something like
<img src="/path/to/my/loading/icon" v-if="loading" />
<ul v-else>
<li v-for="result in results"> ... </li>
</ul>

Related

V-for not working with dynamic data in template

My template has following:
<ul id="example-1">
<li v-for="item in getMenus" :key="item.id">
{{ item.name }}
</li>
</ul>
methods:{
async getMenus() {
this.$axios.setHeader('Content-Type', 'application/json', ['get'])
this.$axios.setHeader(
'Authorization',
'Bearer ' + this.$store.state.auth.Token
)
const roleId = this.$store.state.auth.role.roleId
const url = `/role/${roleId}/menu`
let data = ''
// eslint-disable-next-line vue/no-async-in-computed-properties
const pal = await this.$axios
.$get(url, JSON.stringify(roleId))
.then(function(resp) {
data = resp.data
})
if (pal) {
// eslint-disable-next-line no-console
console.log('hi')
}
return data
}
}
}
Above mentioned is my code. I checked my api its returing data. If i put directly my data as harcoded value then it works, if I use api then it doesnot work. I looke dinto console also that is also clear. I am new to vue. Any help will be highly appreciated.
You can't use async methods in v-for. Define an array in data section of a component and write results in the array at the end of getMenus function. You should call getMenus at some place in your code (for instance in mounted hook):
<li v-for="item in menuList" :key="item.id">
...
// in a component code
data: {
return {
menuList: []
}
},
mounted () {
// if you don't have any initialization after this call you can call it without await
getMenus()
},
methods:{
async getMenus() {
...
// getting results
const { data: menuList } = await this.$axios
.$get(url, JSON.stringify(roleId))
this.menuList = menuList
}
This happens because inside async getMenus method you are returning data before it is even assigned a value. A better way to resolve this issue would be to set a variable in data options like:
data() {
return {
loading: false,
items: [] // This will hold all the getMenus() data
}
},
and inside getMenus update items array like:
created() {
this.getMenus();
},
methods: {
async getMenus() {
this.loading = true;
// All other logic here...
this.$axios.$get(url, JSON.stringify(roleId))
.then(resp => {
this.loading = false;
this.items = resp.data; // Set the response data here...
})
.catch(error => {
this.loading = false;
console.log(error);
})
}
}
and then update your template like:
<li v-for="item in items" :key="item.id">
{{ item.name }}
</li>
In case, your async method is going to take some time to finish you can show a loading text or icon so that user know that at least something is happening instead of looking at a blank screen like:
<template v-if="loading">
Loading...
</template>
<template v-else>
<ul id="example-1">
<li v-for="item in items" :key="item.id">
{{ item.name }}
</li>
</ul>
</template>

ProxyTable doen't work in vuejs when call api

In config/index.js i config like this
proxyTable: {
'/api': {
target: 'http://localhost:44322',
changeOrigin: true
}
},
And this code i call get method.
<template>
<div>
<ul v-if="posts && posts.length">
<li v-for="post of posts" v-bind:key="post.employeeId">
<p><strong>{{post.firstName}}</strong></p>
<p>{{post.lastName}}</p>
<p>{{post.phoneNumber}}</p>
<p>{{post.dateOfBirth}}</p>
<p>{{post.email}}</p>
</li>
</ul>
<ul v-if="errors && errors.length">
<li v-for="error of errors" v-bind:key="error.id">
{{error.message}}
</li>
</ul>
</div>
</template>
<script>
import Axios from 'axios'
export default {
name: 'Axios',
data () {
return {
posts: [],
errors: []
}
},
// Fetches posts when the component is created.
created () {
Axios.get('/api/employee')
.then(response => {
// JSON responses are automatically parsed.
this.posts = response.data
})
.catch(e => {
this.errors.push(e)
console.log(e)
})
}
}
</script>
I want when i call
http://localhost:8080/#/axios
the client call to backend :
http://localhost:44322/api/employee
But nothing happen, i see in header of request the url is :
localhost:8080
i do flow the link of vuejs: https://vuejs-templates.github.io/webpack/proxy.html ,part API Proxying During Development. Any idea for this?
Thanks!!
you would see the request url as http://localhost:8080/api/employee in the browser
and finally the request will be transferd to http://localhost: 44322/api/employee which you won't see in network panel of your browser

How does vuejs react to component data updated asynchronously

I am very new with vuejs and recently started to try to replace some old jquery code that I have and make it reactive with vuejs. The thing is I have a component that gets information from a nodejs server via socket.io asynchronously.
When I get the data and update my component's data I see the changes when I console log it but it does not change the DOM the way I want it to do.
What is the proper way to grab data asynchronously and use it inside a component? I post some parts of my code so you can see it. I will appreciate any advice you can give me. Thanks in advance!
Vue.component('chat', {
data() {
return {
chat: null,
commands: [],
chatOpened: false,
}
},
props: [
'io',
'messages',
'channels',
'connectChat',
'roomChat',
'user',
'userId',
'soundRoute',
],
methods: {
openChat() {
this.chatOpened = true;
},
closeChat() {
this.chatOpened = false;
},
},
created() {
this.chat = this.$io.connect(this.connectChat);
this.commands.push('clear');
let self = this;
$.each(this.channels, function(index, value) {
self.chat.emit('join', {room: index, user: self.user, userId: self.userId}, function(err, cb) {
if (!err) {
users = cb.users;
messages = cb.messages;
if (messages.length > 0) {
self.channels[index].loaded = true;
}
//some more code
}
});
});
console.log(this.channels);
},
template: `
<div>
<div id="container-chat-open-button" #click="openChat" :class="{hide : chatOpened}">
<div>+90</div>
<i class="fas fa-comment-alt"></i>
</div>
<div id="container-chat" class="chat__container" :class="{open : chatOpened}">
<div id="container-chat-close-button" #click="closeChat">
<span>
<div>
<i class="fas fa-comment-alt"></i>
#{{ messages.chat_lobby_icon_title }}
</div>
<i class="icon-arrowdown"></i>
</span>
</div>
<div id="alert-chat" class="chat__container-notifications animated flash"></div>
<div class="row">
<ul>
<li v-for="channel in channels" v-show="channel.loaded === true">Channel loaded</li>
</ul>
</div>
</div>
</div>
`
});
I would expect to see the list of channels with messsages but instead I don't see the list even thought I see my channels with the loaded attribute set to true (by default they all have this attribute set to false).
My guess is that it's this part that is not working as expected.
if (messages.length > 0) {
self.channels[index].loaded = true;
}
The reactive way of doing this is by setting the full object again.
Vue.set(self.channels, index, {
...self.channels[index],
loaded: true
}
EDIT 1:
this.channels.forEach((channel) => {
this.chat.emit('join', {room: index, user: self.user, userId: self.userId}, (err, cb) => {
if (!err) {
users = cb.users;
messages = cb.messages;
if (messages.length > 0) {
Vue.set(self.channels, index, {
...self.channels[index],
loaded: true
}
}
//some more code
}
});
})
You'll need to add support for the rest-spread-operator using babel.

Updating custom component's form after getting a response

I'm trying to load in a Tutor's profile in a custom component with Laravel Spark. It updates with whatever I enter no problem, but the is always empty when loaded.
The component itself is as follows:
Vue.component('tutor-settings', {
data() {
return {
tutor: [],
updateTutorProfileForm: new SparkForm({
profile: ''
})
};
},
created() {
this.getTutor();
Bus.$on('updateTutor', function () {
this.updateTutorProfileForm.profile = this.tutor.profile;
});
},
mounted() {
this.updateTutorProfileForm.profile = this.tutor.profile;
},
methods: {
getTutor() {
this.$http.get('/tutor/current')
.then(response => {
Bus.$emit('updateTutor');
this.tutor = response.data;
});
},
updateTutorProfile() {
Spark.put('/tutor/update/profile', this.updateTutorProfileForm)
.then(() => {
// show sweet alert
swal({
type: 'success',
title: 'Success!',
text: 'Your tutor profile has been updated!',
timer: 2500,
showConfirmButton: false
});
});
},
}
});
Here's the inline-template I have:
<tutor-settings inline-template>
<div class="panel panel-default">
<div class="panel-heading">Tutor Profile</div>
<form class="form-horizontal" role="form">
<div class="panel-body">
<div class="form-group" :class="{'has-error': updateTutorProfileForm.errors.has('profile')}">
<div class="col-md-12">
<textarea class="form-control" rows="7" v-model="updateTutorProfileForm.profile" style="font-family: monospace;"></textarea>
<span class="help-block" v-show="updateTutorProfileForm.errors.has('profile')">
#{{ updateTutorProfileForm.errors.get('profile') }}
</span>
</div>
</div>
</div>
<div class="panel-footer">
<!-- Update Button -->
<button type="submit" class="btn btn-primary"
#click.prevent="updateTutorProfile"
:disabled="updateTutorProfileForm.busy">
Update
</button>
</div>
</form>
</div>
Very new to Vue and trying to learn on the go! Any help is much appreciated!
OK, firstly a bus should be used for communication between components, not within the components themselves, so updateTutor should be a method:
methods: {
getTutor() {
this.$http.get('/tutor/current')
.then(response => {
this.tutor = response.data;
this.updateTutor();
});
},
updateTutor() {
this.updateTutorProfileForm.profile = this.tutor.profile;
}
}
Now for a few other things to look out for:
Make sure you call your code in the order you want it to execute, because you appear to be emitting to the bus and then setting this.tutor but your function uses the value of this.tutor for the update of this.updateTutorProfileForm.profile so this.tutor = response.data; should come before trying to use the result.
You have a scope issue in your $on, so the this does not refer to Vue instance data but the function itself:
Bus.$on('updateTutor', function () {
// Here 'this' refers to the function itself not the Vue instance;
this.updateTutorProfileForm.profile = this.tutor.profile;
});
Use an arrow function instead:
Bus.$on('updateTutor', () => {
// Here 'this' refers to Vue instance;
this.updateTutorProfileForm.profile = this.tutor.profile;
});
Make sure you are not developing with the minified version of Vue from the CDN otherwise you will not get warnings in the console.
I can't see how you are defining your bus, but it should just be an empty Vue instance in the global scope:
var Bus = new Vue();
And finally, your mounted() hook is repeating the created() hook code, so it isn't needed. My guess is that you were just trying a few things out to get the update to fire, but you can usually do any initialising of data in the created() hook and you use the mounted hook when you need access to the this.$el. See https://v2.vuejs.org/v2/api/#Options-Lifecycle-Hooks

I am new to vue js ... can't display loaded data from a php file

Template part :
`<div class="col-sm-6" >
<ul class="list-group" id="pos">
<li class="list-group-item" v-for="(itm, index) in items">
<strong>{{index}} : {{ itm.sub }}</strong> - {{ itm.price }}
</li>
</ul>
</div>`
Script part :
new Vue({
el: '#pos',
http: {
root: '/vuetest',
headers: {
Authorization: 'Basic YXBpOnBhc3N3b3Jk'
}
},
data: {
items: []
},
created:function () {
this.$http.get('index.php').then(function(resp,status,request){
this.items = resp.data;
console.log(this.items); // got data but not displayed in browser
}.bind(this));
}
});
My Source files are from cdnjs.cloudeflare.com:
vue.js (2.1.4)
vue-resource.js (1.0.3).
Well, this isn't that...
created:function () {
this.$http.get('index.php').then(function(resp,status,request){
this.items = resp.data; // this is referring to the current function, and not to vue's scope.
console.log(this.items); // got data but not displayed in browser
}.bind(this));
}
So the correct use is:
created:function () {
var self = this
this.$http.get('index.php').then(function (resp,status,request) {
self.items = resp.data;
console.log(this.items);
});
}
As MU commented above, better you to use Arrows functions, so the "this" will have the scope you want.
mounted () {
}
Then you can access all your Data properties normally with "this".