Reputation: 5024
I have like this code in my app:
<div id="app">
<button v-if="!isLoaded && !isLoading" @click="startLoading()">Start Loading</button>
<div v-if="isLoading">Loading app...</div>
<template v-else>
<img v-show="isLoaded" ref="img" />
</template>
</div>
<script>
new Vue({
el: "#app",
data() {
return {
isLoading: false,
isLoaded: false,
}
},
mounted() {
},
methods: {
startLoading() {
this.isLoading = true;
for (let i = 1; i < 1E9; ++i) {
//Dummy load;
const a = 1;
}
this.isLoading = false;
this.isLoaded = true;
this.$refs.img.src = 'https://cdn.pixabay.com/photo/2018/07/04/11/58/xiamen-3515964__340.jpg';
}
},
})
</script>
In this code, when you click on the "Start Download" button, the message "Loading..." should appear for a while, after which the image will appear. But there is no sign "Loading". Why? Can this be fixed? If so, correct it. (It is undesirable to remove the dummy load. Imagine that we are there very intensively processing some file for the user)
Upvotes: 0
Views: 545
Reputation: 26
You could use events onload
and onerror
:
<template>
<div>
<!-- button -->
<button v-if="!isLoaded && !isLoading" @click="startLoading">Start Loading</button>
<!-- during loading -->
<div v-show="isLoading && !isLoaded">Loading.....</div>
<!-- image show when loaded -->
<img
:src="imgSrc"
v-show="isLoaded"
@load="imgLoadedHandler"
@error="imgFailedHandler" />
</div>
</template>
<script>
export default {
data() {
return {
imgSrc: '',
isLoading: false,
isLoaded: false,
}
},
methods: {
startLoading() {
this.isLoading = true;
this.imgSrc = '...';
},
// called when image loaded
imgLoadedHandler() {
this.isLoaded = true;
this.isLoading = false;
},
// called when image failed to load
imgFailedHandler() {
this.isLoaded = true;
this.isLoading = false;
}
}
}
</script>
Upvotes: 0
Reputation: 90287
If the code execution has to wait for the loop to finish, mark startLoading
as async
(so you can use await
inside of it) and use await
on whatever promises your loop awaits. Basic example:
methods: {
async startLoading() {
this.isLoading = true;
for (let i = 1; i < 1E9; ++i) {
const a = await // your promise here;
// do stuff with `a`
}
this.isLoading = false;
this.isLoaded = true;
this.$refs.img.src = 'https://cdn.pixabay.com/photo/2018/07/04/11/58/xiamen-3515964__340.jpg';
}
}
Docs and examples here.
Upvotes: 1