简体   繁体   中英

Nuxt.js: Start loading indicator from vuex

According to documentation, there is a way to manually start the nuxt loading indicator in a component as such:

export default {
    methods: {
        startLoading() {
            this.$root.$loading.start();
        },
    },
}

Is there any way to toggle the loader from a vuex action? How can I access the $root object from a vuex action?

Sweet! Apparently it can be accessed through the window property which is available on client. It would be advisable to confirm that the action is run on the client, not on server, by checking process.browser :

export const actions = {
    startLoading({ commit }) {
        if (process.browser) {
            window.$nuxt.$root.$loading.start();
        }
        commit('SET_LOADING', true);
    },
    finishLoading({ commit }) {
        if (process.browser) {
            window.$nuxt.$root.$loading.finish();
        }
        commit('SET_LOADING', false);
    },
}

Pretty cool. The actions are called from axios interceptors, so now it indicates loading globally when making any request to the server.

I am using layouts/default.vue file to check if current process is server-side or client-side. Example:

<template>
  <div class="fontFamily">
    <Nuxt v-if="isClient" />
    <div v-else class="container">
        <img class="logo" src="~/assets/images/logo-hori.png" />
    </div>
  </div>

</template>

<script>
export default {
    data() {
        return {
            isClient: false
        }
    },
    beforeMount () {
        this.isClient = false
    },
    mounted() {
        this.isClient = true
    }
}
</script>

If it is in server side, I return logo of app, and then return app if in client side. You can access store as well after mounted

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