Vue之vue-resource的一般用法Es5

Vue-resource主要用来做Vue应用与后端数据的交互,我们在使用时有时会要用到Es5的写法,但由于Es5与Es6的语法原因导致写法各异,甚至很多教程都迷惑用错,下面列出几种常见的用法,备查。

依赖:

vue-resource
vue 1.x

官方的Es6标准写法

这是官方标准的Es6的简单写法:
<pre>
{
// GET /someUrl
this.$http.get('/someUrl').then((response) => {
// success callback
}, (response) => {
// error callback
});
}
</pre>

不用箭头函数的写法:
<pre>
//定义json资源的url
var resource_url = 'http://www.example.com/tweets?q=vuejs&count=10';

//主要代码区,位于vue实例的methods代码段内
methods:{
load: function() {
this.$http.get(this.resource_url).then(function(response) {
console.log(response)
}, function(error){
console.log(error)
})
}
}
</pre>

更深入点参看下面
<pre>
{
// POST /someUrl
this.$http.post('/someUrl', {foo: 'bar'}).then((response) => {

// get status
response.status;

// get status text
response.statusText;

// get 'Expires' header
response.headers.get('Expires');

// set data on vm
this.$set('someData', response.body);

}, (response) => {
// error callback
});
}
</pre>

详细文档参看

vue-resource Es5的写法

基本用法如下(此处省略了对于错误处理):

<pre>
//定义json资源的url
var apiUri = "http://www.example.com/tweets?q=vuejs&count=10";
{
getPositions: function() {
//get the url
this.$http.get(apiUri + 'pages/?pageid=1&limit=10',function (positions) {
// success callback
this.$set('positions', positions);
console.log(this.positions);
});
}
}
</pre>

一般容易出错的地方主要在关于错误处理区的位置
<pre>
//定义json资源的url
var apiUri = "http://www.example.com/tweets?q=vuejs&count=10";
{
getPositions: function() {
//get the url
this.$http.get(apiUri + 'pages/?pageid=1&limit=10',function (positions) {
// success callback
this.$set('positions', positions);
console.log(this.positions);
}).error(function(data, status, request) {
// error callback
console.log('Fail,网址或相关错误!\n错误码:' + status + "\nrequest:" + request);

    });
}

}
</pre>

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 【阅读原文】 不断学习的过程,就是追求新知识的过程。有时候,一本书往往能给人带来莫大的收益。看过《三国演义》的人都...
    圆禄阅读 572评论 0 0
  • 能放下何尝不是一种逃避。看的开求得心境自在,却失物事纷华。人生美好,若是以苦为本反是失了色彩。然而苦味本就存于生活...
    郁衡子阅读 587评论 1 2
  • 秦凯说,我想要你。我说,好,正好我也想睡你。 — 01 — 我和秦凯的关系算是特殊的朋友吧,用王小波的话来讲,就是...
    明明很爱很爱阅读 439评论 1 0
  • 最近,很多事情我都放手让孩子们自己去做,不再每天无时无刻地“监视”着他们,他们需要自己学会组织、安排,需要更多的自...
    summer凌霄阅读 130评论 0 0