vue请求后台数据的几种方式
常用的为:vue-resource、 axios、fetch-jsonp
1、vue-resource 官方提供的 vue的一个插件 ①安装:在项目根目录进行安装:cnpm install vue-resource --save
save说明:将此插件名插入到pachage.json文件中,别人在使用时,直接npm install,就会安装package.json里的所配置的软件插件名称了。
②引入vue-resource
在main.js中引入这个插件,并使用这个插件
import VueResource from vue-resource
Vue.use(VueResource );
③示例:
export default{ data(){ return { msg:我是一个首页组件msg, flag:true, list:[] } }, methods:{ getData(){ //请求数据 var api=http://www.phonegap100.com/appapi.php?a=getPortalList&catid=20&page=1; this.$http.get(api).then((response)=>{ console.log(response); //注意this指向 this.list=response.body.result; },function(err){ console.log(err); }) } }, mounted(){ /*生命周期函数*/ this.getData(); } }
2、
axios 的使用
1、安装 cnpm install axios --save 2、哪里用哪里引入axios
import Axios from axios; export default{ data(){ return { list:[] } }, methods:{ getData(){ var api=http://www.phonegap100.com/appapi.php?a=getPortalList&catid=20&page=1; Axios.get(api).then((response)=>{ this.list=response.data.result; }).catch((error)=>{ console.log(error); }) } }, mounted(){ /*生命周期函数*/ this.getData(); } }
3、fetch-jsonp 不受跨域限制
安装 cnpm i fetch-jsonp -S
用法 : 在项目中引入 import fetchJsonp from fetch-jsonp
let domain=`http://api.douban.com/v2/movie/top250` fetch(this.domain,{ start:0, count:20, method:GET, mode:no-cors }).then(response=>{ console.log(response) console.log(response.json()) return response.json() }).then(res=>{ console.log(res) }).catch(e=>{ console.log(e) })