vue3 axios使用 配置
1. 第一步肯定是安装 axios: npm install axios --save
2. 创建一个文件输出axios,我这里在src下创建的utils/util.js
3. util.js
import axios from 'axios'
const url = process.env.NODE_ENV==='production'? 'http://xxxx.com(线上地址)' : 'http://www.xiongmaoyouxuan.com/api'
const $http = axios.create({
baseURL: url, // 所有的请求地址前缀部分
timeout: 60000, // 请求超时时间毫秒
withCredentials: true, // 异步请求携带cookie
headers: {
// 设置后端需要的传参类型
'Content-Type' : 'application/x-www-form-urlencoded'
},
})
// 添加请求拦截器
$http.interceptors.request.use(
function (config) {
// 设置加载进度
return config
},
function (error) {// 发送失败
return Promise.reject(error)
}
)
// 添加响应拦截器
$http.interceptors.response.use(
function (response) {
// 关闭加载进度
return response
},
function (error) {
return Promise.reject(error)
}
)
const $get = function(url,param,fn){ // get方法
$http.get(url,{params:param}).then(function(res){
fn(res.data)
}).catch(function(err){
console.log(err)
})
}
const $post = function(url,param,fn){ // post方法
this.$http.post(url,{params:param}).then(function(res){
fn(res.data)
}).catch(function(err){
console.log(err);
})
}
export{$get, $post,} // 导出方法
4. 页面使用 util.js
<template>
<div class="aa">
aa
</div>
</template>
<script>
import {onMounted} from 'vue'
import {$get} from '../../../utils/util'
export default {
setup() {
const getTest = () => {
$get(
"/tabs?sa=",
{},
res => {
console.log('测试', res)
}
)
}
onMounted(() => {
getTest()
})
return {}
},
}
</script>
<style scoped>
</style>
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!