简体   繁体   中英

Loading spinner doesn't work during first GET request which is executed on mounted

In the code below you can see that If isLoading is true, I render a spinner component. By default isLoading is set to false and before every GET request, I set it to true and at the end of the GET request when everything has loaded, I set it back to false.

Weirdly enough when the GET requests in the watch go through, everything works fine and I see the spinner until the GET request is done, HOWEVER, when I mount the component I don't see a spinner before the first GET request which is made inside the mounted() lifecycle hook and I have no clue why.

I used console.log(this.isLoading) before and after setting isLoading to true to check if everything is alright and it seems like it is. So why am I not seeing the spinner before the first GET request on mounted()?

<div v-if='isLoading' class="spinner-container">
    <spinner></spinner>
 </div>
<div v-else>
    Content
</div>

<script>
    data(){
        return {
            sights: null,
            type: null,
            range: null,
            isLoading: false
        }
    },
    mounted(){
        this.isLoading = true
        axios.get('/getSights/' + this.lat + '/' + this.lng + '/' + this.type + '/' + this.range + '/' + this.nextPageToken)
        .then(response => {
            this.sights = response.data.result.results
            this.isLoading = false
        }).catch((error) => console.log(error));
    },
    watch: {
        type: function () {
            this.isLoading = true
            axios.get('/getSights/' + this.lat + '/' + this.lng + '/' + this.type + '/' + this.range)
            .then(response => {
                this.sights = response.data.result.results
                this.isLoading = false
            }).catch((error) => console.log(error));
        },
        range: function(){
            this.isLoading = true
            axios.get('/getSights/' + this.lat + '/' + this.lng + '/' + this.type + '/' + this.range)
            .then(response => {
                this.sights = response.data.result.results
                this.isLoading = false
            }).catch((error) => console.log(error));
        },
</script>

You should wait till all of the component and child components are rendered. Read more here

This snippet should work for your mounted function:

mounted() {
  this.$nextTick(()=> this.isLoading = true)
  axios.get('/getSights/' + this.lat + '/' + this.lng + '/' + this.type + '/' + this.range + '/' + this.nextPageToken)
  .then(response => {
    this.sights = response.data.result.results
    this.isLoading = false
  }).catch((error) => console.log(error));
},

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM