在vue项目开发中,随着项目的迭代,接口会越来越多,为了后期维护方便,建议在组件中不要写接口的地址,而将组件都写在一个专门管理接口的文件中,以下是我平时开发中常用的方式
1、先在vue.config.js文件中加入设置代理
devServer: {
proxy: {
"/api": {
target: "http://www.baidu.com",
changeOrigin: true,
pathRewrite: {
"^/api": ""
}
}
}
}
2、在src下面创建api文件夹,然后创建一个接口文件config.js
// config.js
const api = process.env.NODE_ENV === "development" ? "/api" : "http:baidu.com";
// api接口
export const homeinfo= api + "/homeinfo";
export const posttest= api + "/posttest";
3、在api文件夹中加index.js文件
// index.js
import axios from "axios"; // 导入axios
import { homeinfo, posttest } from "./config";
axios.defaults.withCredentials = true; // 跨域需要发送cookie时要加这行代码
export default {
home() {
return axios.get(homeinfo); // get请求
},
postrequest(param1, param2){ // post请求
return axios.post(posttest, {
param1,
param2
})
}
};
4、在组件中使用
import api from "api"
handle() {
api.home()
.then(res => {
const data = res.data
}
})
},
postrequest(param1, param2) {
api.home(param, param2)
.then(res => {
const data = res.data
}
})
},
以上就是使用步骤,如有好的建议,欢迎留言
网友评论