1、npm安装
cnpm install axios -S
cnpm install qs -S
2、封装axios.js
import router from "../router/index.js";
import { Toast } from 'vant';
import axios from 'axios'
import qs from "qs";
import { baseURL } from './common.js'
axios.defaults.baseURL = baseURL;
axios.defaults.timeout = 10000;
axios.defaults.headers['X-Requested-With'] = 'XMLHttpRequest';
axios.defaults.withCredentails = true;
axios.interceptors.request.use(config => {
if(localStorage.getItem('token')){
config.headers['token'] = localStorage.getItem('token');
}
return config;
}, error => {
return Promise.reject(error);
})
axios.interceptors.response.use(
response => {
if (response.status === 200) {
return Promise.resolve(response);
} else {
return Promise.reject(response);
}
},
error => {
if (error.response.status) {
switch (error.response.status) {
case 404:
Toast.fail('网络请求不存在');
break;
case 500:
Toast.fail('内部服务器错误');
break;
default:
Toast.fail(error.response.data.msg);
}
return Promise.reject(error.response);
}
}
);
export function get(url, params = {}) {
return new Promise((resolve, reject) => {
axios.get(url, {
params: params
}).then(res => {
if (res.data.code == -2000) {
Toast.fail(res.data.message);
localStorage.clear();
setTimeout(() => {
router.replace({
path: '/login',
query: {
redirect: router.currentRoute.fullPath
}
});
}, 1000);
return;
} else if (res.data.code !== 200) {
Toast.fail(res.message);
}
resolve(res.data);
}).catch(err => {
Toast.fail('网络请求错误');
reject(error.data)
})
});
}
export function post(url, params = {}) {
return new Promise((resolve, reject) => {
axios.post(url, params).then(res => {
if(res.data.code == -2000){
Toast.fail(res.data.message);
localStorage.clear();
setTimeout(() => {
router.replace({
path: '/login',
query: {
redirect: router.currentRoute.fullPath
}
});
}, 1000);
}else if (res.data.code !== 200) {
Toast.fail(res.data.message);
}
resolve(res.data);
}).catch(error => {
Toast.fail('网络请求错误');
reject(error)
})
});
}
var http = {
get,
post
};
export default http;
3、main.js全局引入axios
在vue3.0 中注入全局方法不是在prototype 上挂载了 而是在config.globalProperties 属性上,我在http 前面加个$ 符号还是继承vue2的规范习惯代表全局;
import axios from './utils/axios.js';
const app = createApp(App);
app.config.globalProperties.$http=axios;
app.use(store).use(router).use(Vant).mount('#app')
4、页面中使用axios请求接口并渲染数据
getCurrentInstance() 代表全局上下文,ctx 相当于Vue2 的this , 但是特别注意ctx 代替this 只适用于开发阶段,等你放到服务器上运行就会出错, 错误写法:
// 生产环境下 ctx下获取不到$http
const $http = getCurrentInstance().ctx.$http;
正确解决方案:查看官方文档 const internalInstance = getCurrentInstance() internalInstance.appContext.config.globalProperties // 访问 globalProperties
<template>
<div class="home">
<van-swipe :autoplay="3000">
<van-swipe-item v-for="(item,index) in data.swiper" :key="index">
<img :src="item" />
</van-swipe-item>
</van-swipe>
</div>
</template>
<script>
import { getCurrentInstance,reactive } from 'vue'
export default {
setup() {
const $http = getCurrentInstance().appContext.config.globalProperties.$http;
console.log('打印一下看看')
console.log(getCurrentInstance())
var data = reactive({
swiper: [],
})
$http.post("index/getBanner").then(res => {
if (res.code == 200) {
data.swiper = res.data;
}
})
return {
data
};
},
};
</script>
|