vue-resource调用promise取数据方式详解

2020-06-14 05:59:33易采站长站整理

}, function(value) {
// failure
});

下面我们来直接使用:

假如我们请求下面这个json文件:


// 请求成功
{
"code": 0,
"msg": "get member success",
"content": {
"plank_id": "1",
"start_at": "1234567890",
"status": "3",
"members_num": 1,
"members": [
{
"id": "14",
"name": "",
"avatar": "",
"status": "3"
}
] },
"is_mobile_user": false,
"jssdk": {
"appId": "wxec4d172a4f73ee6f",
"timestamp": "1490367697",
"nonceStr": "58d534d1b536a",
"signature": "d8d8ceb0f39ddeb3085fd197e5df5caddb1f1ba1"
}
}

// 请求失败
{
"code": 1,
"msg": "错误信息",
"content": "",
"is_mobile_user": true,
"jssdk": {
"appId": "wxec4d172a4f73ee6f",
"timestamp": "1487750749",
"nonceStr": "58ad465dd5ba5",
"signature": "4aa01f5a89ce79ee4c53249e0cdb84800f841004"
}
}

get 传统的写法


import {MessageBox} from 'mint-ui';
this.$http.get(dataUrl)
.then(function (response) { // 请求成功
let data = response.data;
if (data.code === 0) {
this.content = data.content; // 取到数据
} else {
MessageBox('提示', data.msg);
}
}, function (response) { // 请求失败
MessageBox('提示', response.data.msg);
})

get ES6的语法 直接用解构赋值和剪头函数的方式


import {MessageBox} from 'mint-ui';
this.$http.get(dataUrl)
.then(({data:{code, content, jssdk, msg}}) => { // 请求成功
if (data.code === 0) {
this.content = content; // 取到数据
} else {
MessageBox('提示', msg);
}
}, ({data:{msg}}) => { // 请求失败
MessageBox('提示',msg);
});

post 传统的语法


let group_id = this.$route.params.id;
let data = {
group_id: group_id,
mobile: this.mobile,
code: this.smsCode,
name: this.memberName
};
import {MessageBox} from 'mint-ui';
this.$http.post(checkUrl, data)
.then(function (response) { // 请求成功
let data = response.data;
if (data.code === 0) {
this.content = data.content; // 取到数据
} else {
MessageBox('提示', data.msg);
}
}, function (response) { // 请求失败
MessageBox('提示', response.data.msg);
});

post ES6的语法,直接用解构赋值和剪头函数的方式