Vue.js学习(9)-Vue.js通过Http请求数据 vue-resource

  1.请求数据的模块vue-resource   https://github.com/pagekit/vue-resource

  •   vue-resource  是官方提供的vue的一个插件
  •   axios
  •   fetch-json

2.模块初始化

npm install vue-resource --save

3.基本语法

// 传统写法
this.$http.get('/someUrl', [options]).then(function(response){
    // 响应成功回调
}, function(response){
    // 响应错误回调
});
// Lambda写法
this.$http.get('/someUrl', [options]).then((response) => {
    // 响应成功回调
}, (response) => {
    // 响应错误回调
});

支持的http方法

vue-resource的请求API是按照REST风格设计的,它提供了7种请求API:

  • get(url, [options])
  • head(url, [options])
  • delete(url, [options])
  • jsonp(url, [options])
  • post(url, [body], [options])
  • put(url, [body], [options])
  • patch(url, [body], [options])

option属性

发送请求时的options选项对象包含以下属性:

参数类型描述
urlstring请求的URL
methodstring请求的HTTP方法,例如:'GET', 'POST'或其他HTTP方法
bodyObjectFormData stringrequest body
paramsObject请求的URL参数对象
headersObjectrequest header
timeoutnumber单位为毫秒的请求超时时间 (0 表示无超时时间)
beforefunction(request)请求发送前的处理函数,类似于jQuery的beforeSend函数
progressfunction(event)ProgressEvent回调处理函数
credentialsboolean表示跨域请求时是否需要使用凭证
emulateHTTPboolean发送PUT, PATCH, DELETE请求时以HTTP POST的方式发送,并设置请求头的X-HTTP-Method-Override
emulateJSONboolean将request body以application/x-www-form-urlencoded content type发送

 

4.Vue.js通过vue-resource进行http数据请求

  • 需要安装vue-resource模块

npm install vue-resource --save

  • main.js引入 vue-resource
  • 调用 Vue.use(VueResource);
  • 在组件中里面直接使用

this.$http.get(地址).then(function(response){})

 

实现如下:

F:\test\vue\vuedemo02>npm install vue-resource --save

main.js

import VueResource from 'vue-resource'
Vue.use(VueResource);

Home.vue

<template>
    <div>
      <br>
      <hr>
      <button @click="getData()">请求数据</button>
      <br>
      <ul>
        <li v-for="item in list">
          {{item.title}}
        </li>
      </ul>
    </div>
</template>

<script>
    export default {
        name: "Home",
      data(){
          return{
            msg:"Home.vue是一个首页组件",
               list:[],
          }
      },
      methods:{
          getData(){
        var api = "http://www.phonegap100.com/appapi.php?a=getPortalList&catid=20&page=1";
        this.$http.get(api).then(function (response) {
          console.log(response);
          this.list = response.body.result;
        },function (err) {
          console.log(err);
        })
        }
      },
      mounted(){
       this.getData();
      },
    }
</script>

 

  • 4
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值