13.Axios fetchJsonp请求数据

内容:Axios请求数据,fetchJsonp请求数据
一、Axios请求数据
由于Axios是第三方库用法和vue-resource有点区别
(1)安装:
npm install axios --save 或者 cnpm install axios --save
—save是为了将安装的信息写入package.json文件中,方便别人使用项目时不会出问题
(2)引入
Axios是在哪个文件要用就在那个文件引入,直接再vue文件中引入;写法如下:
import Axios from ‘axios’;
(3)用法:

 Axios.get(api).then(response=>{
        console.log(response);
      }).catch(function (error) {
    console.log(error);
  }).finally(function () {
    // always executed
  })
    }

注:在这里先开始用的是function(response)但是下面this.list获取不到,换成了箭头函数就可以了
完整例子:

<template>
  <div id="app">
     <button @click="getdata()">请求数据</button>
  <ul>
    <li v-for="(item,key) in list">{{item.title}}</li>
   
    </ul>
  </div>
</template>

<script>
/**  
axios使用
1.安装
 npm install axios --save
2.引入
哪里使用,哪里引入,直接再vue文件中引入
3.用法:

 */
import Axios from  'axios';
export default {
  name: 'app',
  data () {
    return {
      msg: 'Welcome to Your Vue.js App',
      list:[]
    }
  },methods:{
    getdata(){
      var api='http://www.phonegap100.com/appapi.php?a=getPortalList&catid=20&page=1';
     // Axios.get(api).then(function(response){

      Axios.get(api).then(response=>{
        console.log(response);
        this.list=response.data.result;
        
      }).catch(function (error) {
    console.log(error);
  }).finally(function () {
    // always executed
  })
    }
  },mounted(){
    this.getdata();
  }
}
</script>

<style lang="scss">

</style>

二、jsonp 请求数据
1.安装
npm install axios --save 或者 cnpm install axios --save
2.引入:

import Jsonp from 'jsonp';

3.使用

jsonp('http://www.example.com/foo', null, (err, data) => {
  if (err) {
    console.error(err.message);
  } else {
    console.log(data);
  }
});
在js文件中的使用需要const jsonp = require('jsonp');加载一下

完整例子

 getdata(){
   var api='http://www.phonegap100.com/appapi.php?a=getPortalList&catid=20&page=1';
   //const jsonp = require('jsonp');
   Jsonp(api, null, (err, data) => {
  if (err) {
    console.error(err.message);
  } else {
    this.list=data.result;
    console.log(data.result);

  }
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值