前言:分别有兩種封裝方法适用于vue.js和uniapp;第一種:全局注冊,通過this調用,不需要import引入js檔案。第二種:需要請求接口的頁面還要import一下。
ps:下面代碼示例是uniapp項目
目錄結構
![](https://img.laitimes.com/img/_0nNw4CM6IyYiwiM6ICdiwiIyVGduV2YfNWawNyZuBnLyIDO1EDNxETM1ITMxAjMwIzLc52YucWbp5GZzNmLn9Gbi1yZtl2Lc9CX6MHc0RHaiojIsJye.png)
第一種封裝
1:在項目根目錄建立common目錄http.js檔案
http.js檔案
//伺服器位址
const service = "域名/ip位址";
module.exports = (params) => {
let url = params.url;
let method = params.method;
let header = params.header || {};
let data = params.data || {};
// 請求方式 GET POST
if (method) {
method = method.toUpperCase(); // 小寫轉大寫
if (method == "POST") {
header = {
"content-type": "application/x-www-form-urlencoded"
}
}
}
// 發起請求 加載動畫
if (!params.hideLoading) {
uni.showLoading({
title: "加載中"
})
}
// 發起網絡請求
uni.request({
url: service + url,
method: method || "GET",
header: header,
data: data,
dataType: "json",
sslVerify: false, // 是否驗證ssl證書
success: res => {
console.log(res)
if (res.data.code && res.data.code != 200) {
// api錯誤
uni.showToast({
title:res.data.info,
icon:'none'
})
return;
}
typeof params.success == "function" && params.success(res.data);
},
fail: err => {
uni.showToast({
title:res.data.info,
icon:'none'
})
typeof params.fail == "function" && params.fail(err.data);
},
complete: (e) => {
console.log("請求完成");
uni.hideLoading()
typeof params.complete == "function" && params.complete(e.data);
return;
}
})
}
2:在main.js注冊全局
main.js檔案
import Vue from 'vue'
import App from './App'
import http from './common/http.js'
const msg = (title, duration=1500, mask=false, icon='none')=>{
//統一提示友善全局修改
if(Boolean(title) === false){
return;
}
uni.showToast({
title,
duration,
mask,
icon
});
}
Vue.config.productionTip = false
Vue.prototype.http = http
Vue.prototype.$api = {msg};
App.mpType = 'app'
const app = new Vue({
...App
})
app.$mount()
3:調用接口
xxx.vue檔案
methods: {
//初始化資料
getData() {
this.http({
url: "api/index/getImg",
method:"GET",
success: res => {
console.log(res)
},
fail: err => {
console.log(res)
}
})
},
}
第二種封裝
1:在項目根目錄建立common目錄service.js檔案
service.js
const service = "域名/ip位址";
export default{
service
}
2:調用接口
xxx.vue檔案
<script>
import apis from "@/common/service.js"
methods: {
getData() {
uni.request({
url: apis.service + "api/task/recommendFriends",
data: {},
success: res => {
console.log(res)
}
})
}
}
</script>