内容: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);
}