Vue3 实现请求接口loading以及请求失败提示
1.工具
aixos vuex
2.主要应用
axios: 拦截器
请求拦截器:service.interceptors.request
响应拦截器:service.interceptors.response
vuex
state
mutations
actions
3.思路
1通过axios拦截器获取请求和相应的状态,2通过actions异步控制mutation修改state,3页面使用state
4.代码
-
通过axios拦截器获取请求和相应的状态
//axios.js import axios from 'axios'; // 引入axios axios.defaults.baseURL = '//baidu.com'; // 设置默认域名 const service = axios.create({ timeout: 10000, headers: { 'content-type': 'application/x-www-form-urlencoded' }, withCredentials:true // 携带cookie, (后端需要跨域配置,不需要就去掉) }) //请求拦截 service.interceptors.request.use( config => { // 请求前逻辑 return config }, error => { Promise.reject(error) } ) //响应拦截 service.interceptors.response.use( response => { // 响应前逻辑 const res = response.data; return res }, error => { console.log(error) } ) export default service //暴露出service
2.通过actions异步控制mutation修改state
// store/index.js
import { createStore } from "vuex"; // 引入vuex
export default createStore({
state: {
loading:false // loading状态
},
getters:{
},
mutations: {
setLoadingState(state,loadingState) {
state.loading = loadingState
}
},
actions: {
changeLoadingstate({ commit }, loadingState){
return new Promise((resolve,reject) => {
commit('setLoadingState',loadingState)
resolve(loadingState)
})
}
},
modules: {}
});
//axios.js
+ import store from "../store"; // 引入store
service.interceptors.request.use(
config => {
+ store.dispatch('changeLoadingstate',true) //请求发出去改变loading状态
return config
},
error => {
Promise.reject(error)
}
)
// response interceptor
service.interceptors.response.use(
response => {
const res = response.data;
+ store.dispatch('changeLoadingstate',false) //响应收到前改变loading状态
return res
},
error => {
console.log(error)
}
)
3.页面使用state
// page.vue
<template>
<div class="loading" v-if="loading"></div>
</template>
<script lang="ts">
import { defineComponent, onMounted, ref, computed, watch} from "vue";
import { useStore } from 'vuex';
export default defineComponent({
name:'page.name',
props:{
},
components: {
},
setup(props,context){
const store = useStore()
const loading = computed(() => {
return store.state.loading
})
watch(() => loading.value, () => {
//
})
return {
loading
}
},
emits: ['']
})
</script>
<style>
</style>