请求封装
const BASE_URL = 'http://localhost:8888';
const http = ({
url,
data = {},
method = 'get',
header = {},
}) => {
let token = uni.getStorageSync('token') || '';
if (!url) return;
return new Promise((resolve, reject) => {
uni.request({
url: BASE_URL + url,
method,
data,
header: {
token,
...header
},
success: (res) => {
resolve(res)
},
fail: (err) => {
reject(err);
}
});
})
}
export default http;
main.js配置
import App from './App';
//引入封装的js文件
import http from '@/utils/http.js'
// #ifdef VUE3
import {
createSSRApp
} from 'vue';
export function createApp() {
const app = createSSRApp(App);
//配置全局属性
app.config.globalProperties.$http=http
return {
app
}
}
// #endif
在xxx.vue中的应用
<script>
import {
onMounted,
getCurrentInstance
} from "vue";
export default {
setup() {
const {
proxy
} = getCurrentInstance();
onMounted(() => {
proxy.$http({
url: 'xxx',
data: {
},
method: ''
}).then(res => {
})
})
}
}