我想在Vue组件之外使用$nuxt.$loading
https://nuxtjs.org/api/configuration-loading/。我创建了用于命中API的中央js。
services / api-client.js
import axios from "axios";
import { state } from '../store/modules/sessions';
const axiosClient = axios.create({
baseURL: process.env.BASE_URL,
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
'X-Api-Key': state().token
}
});
axiosClient.interceptors.request.use(function (config) {
// show nuxt loading here
return config;
}, function (error) {
return Promise.reject(error);
});
axiosClient.interceptors.response.use(function (response) {
// hide nuxt loading here
if (response.data.status.code != 200) {
throw { message: response.data.status.errorDetail };
} else {
return response;
}
}, function (error) {
// hide nuxt loading here
return Promise.reject(error);
});
export default {
all(path) {
return axiosClient.get(path);
},
show(path) {
return this.all(path);
},
create(path, params) {
return axiosClient.post(path, params);
},
update(path, params) {
return axiosClient.put(path, params);
}
};
,并从我的 index.vue 中调度触发Api请求的操作。
<template>
<div>
<h1> Welcome </h1>
</div>
</template>
<script>
export default {
created() {
this.$store.dispatch('getInsiders', this);
}
}
</script>
答案 0 :(得分:1)
您真的需要声明自己的axios客户端吗?
执行此操作的标准方法是使用nuxt的axios模块,然后在您的插件中对其进行自定义。
nuxt.config.js
constructor(public rest: RestService, private route: ActivatedRoute, private router: Router, private myService: MyService) { }
ngOnInit() {
this.myService.currentOrders.subscribe(orderData =>
this.setOrdersArray(orderData));
this.myService.currentReturns.subscribe(returnData =>
this.setReturnsArray(returnData));
this.setOrderValues(this.orders);
this.onChangeReturnType();
}
〜/ plugins / axios
modules: ['@nuxtjs/axios'],
plugins: ['~/plugins/axios']
axios模块将自动管理加载状态。 尽管您仍然可以禁用单个请求的进度
例如组件/动作
export default ({ $axios, redirect }) => {
$axios.onError(error => {
// do anything you need
})
}
答案 1 :(得分:1)
您的问题的解决方案是下面的代码。 请尝试这个。
export default function({ $axios, store }: any) {
$axios.onRequest((config: any) => {
store._vm.$nextTick(() => {
store._vm.$nuxt.$loading.start()
return config
})
})
$axios.onResponse((response: any) => {
store._vm.$nextTick(() => {
store._vm.$nuxt.$loading.finish()
return response
})
})
$axios.onError((error: any) => {
store._vm.$nextTick(() => {
store._vm.$nuxt.$loading.finish()
return Promise.reject(error)
})
})
}