vue3.0封装axios:
程序员文章站
2022-06-22 23:45:08
vue3.0封装网络模块:3.0和2.0差距不大,就引入方式有些区别,下面请看操作:第一步:在scr里面创建一个network文件夹,在network文件夹里面创建三个文件第二步:第一个文件夹 config.js,在里面写入以下:export const METHOD = { GET: "get", POST: "post", PUT: "put", DELETE:"delete"};export const PATH = { index: "/index...
vue3.0封装网络模块:
第一步:
第二步:
export const METHOD = {
GET: "get",
POST: "post",
PUT: "put",
DELETE:"delete"
};
export const PATH = {
index: "/index.json",
details: "/detail.json",
};
import axios from "axios";
import { METHOD } from "./config";
const instance = axios.create({
baseURL: 'http://localhost:8080',
timeout: 5000,
});
// let loading = null;
// 添加请求拦截器
instance.interceptors.request.use(
function(config) {
return config;
},
function(error) {
// 对请求错误做些什么
return Promise.reject(error);
}
);
// 添加响应拦截器
instance.interceptors.response.use(
function(response) {
return response;
},
function(error) {
// 对响应错误做点什么
return Promise.reject(error);
}
);
export function request(method, url, parmas) {
switch (method) {
case METHOD.GET:
return GET(url, parmas);
case METHOD.POST:
return POST(url, parmas);
case METHOD.PUT:
return PUT(url, parmas)
case METHOD.DELETE:
return DELETE(url, parmas)
}
}
function GET(url, params) {
return instance.get(url, params);
}
function POST(url, params) {
return instance.post(url, params);
}
function PUT(url, params) {
return instance.put(url, params);
}
function DELETE(url, params) {
return instance.delete(url, params);
}
import { METHOD, PATH } from "./config";
import { request } from "./core";
const APIClient = {
index(params) {
return request(METHOD.GET, PATH.index, params);
},
details(params) {
return request(METHOD.GET, PATH.details, params);
},
};
export default APIClient;
第三步:
注意2.0与3.0区别:
// import axios from 'axios'
const app = createApp(App)
// app.config.globalProperties.$axios = axios
import http from './network/index'
app.config.globalProperties.$http = http
app.use(store).use(router).use(http).use(Vant).mount('#app')
第四步:
<script>
// @ is an alias to /src
import { defineComponent, reactive, ref, getCurrentInstance } from "vue";
import Grid from "../components/Grid";
export default defineComponent({
name: "Home",
components: { Grid },
setup() {
const state = reactive({
swiper: [],
pop: [],
pus: [],
list: [],
});
const value = ref("");
const { ctx } = getCurrentInstance();
ctx.$http.index().then((res) => {
console.log(res);
state.swiper = res.data.data.swiperList;
state.pop = res.data.data.recommendList;
state.pus = res.data.data.weekendList;
state.list = res.data.data.iconList;
});
const gotodetails = () => {
ctx.$router.push({ path: "/about" });
};
return { state, value, gotodetails };
},
});
</script>
本文地址:https://blog.csdn.net/weixin_53571467/article/details/114302230