mpvue封装数据请求(一)
(一)在utils文件中新建httppost.js文件,用于请求数据封装`const host=""//如果有则输入function request(url,method,data,header={}){wx.showLoading({title:'正在加载中....'})return new Promise((resolve,reject)=>{wx.requ.
·
(一)在utils文件中新建httppost.js文件,用于请求数据封装
`
const host=""//如果有则输入
function request(url,method,data,header={}){
wx.showLoading({
title:'正在加载中....'
})
return new Promise((resolve,reject)=>{
wx.request({
url:url,
method:method,
data:data,
header:{
'content-type':'application/json'
},
success:function(res){
wx.hideLoading();
resolve(res.data)
},
fail:function(res){
wx.hideLoading();
reject(res);
},
complete:function(res){
wx.hideLoading();
}
})
})
}
//封装get方法
function get(obj){
return request(obj.url,'GET',obj.data)
}
//封装post方法
function post(obj){
return request(obj.url,'POST',obj.data)
}
(二)在main.js中引入原型(最外层的main.js,用作全局变量)
import HttpPost from "./utils/httppost';//引入
Vue.prototype.$wxhttp=HttpPost;//作为全局变量
(三)在组件中使用
this.$wxhttp.get({
url:"/login",//连接的网址
data:{};//需要的参数
}).then((res)=>{
console.log(res)
})
更多推荐
已为社区贡献9条内容
所有评论(0)