Reputation: 1564
I want to display my custom loading on all axios request globally
for that I've made a plugin for axios to call it like this
plugins/axios.js
export default function ({ app, $axios, redirect, store }, inject) {
$axios.onRequest(config => {
this.$nuxt.$loading.start()
})
$axios.onError(error => {
this.$nuxt.$loading.finish()
})
}
but It get error because we don't have this here .
so how can I modify this code ?
Upvotes: 1
Views: 1206
Reputation: 376
The nuxt loading property is used to track pages load status. This is an internal component that you can replace with custom component:
// nuxt.config.js
export default {
loading: '~/components/YourLoadingComponent.vue'
}
But it is not the same feature that set a loading status for your HTTP requests. I recomend you to create a component to manage the loading status for your HTTP requests, and you can manage the current loading status with Vuex, and then modify the store from your axios.js
plugin.
// axios.js plugin
export default function ({ $axios, store }) {
$axios.onRequest(config => {
store.dispatch('setLoadingStatus', true)
})
$axios.onError(error => {
store.dispatch('setLoadingStatus', false)
})
}
Then you Vuex store can manage the request status:
// store/index.js file
export const state = () => ({
isRequestLoading: false
})
export const mutations = {
saveLoadingStatus(state, payload) {
state.isRequestLoading = payload
}
}
export const actions = {
setLoadingStatus({ commit }, status) {
commit('saveLoadingStatus', status)
}
}
And very simple example component:
<template>
<div>
<p v-if="isRequestLoading">Is Loading</p>
<p v-else>Request completed</p>
</div>
</template>
<script>
import { mapState } from 'vuex'
export default {
computed: {
...mapState({
isRequestLoading: (state) => state.isRequestLoading
})
}
}
</script>
You can set a loading bar or spinner to display in your window inside this component.
Upvotes: 1