vue-resource:
推薦教程:https://www.runoob.com/vue2/vuejs-ajax.html
1. 需要安裝vue-resource模塊, 注意加上 --save
npm install vue-resource --save / cnpm install vue-resource --save
2. main.js引入 vue-resource
import VueResource from 'vue-resource';
3. main.js
Vue.use(VueResource);
4. 在組件里面直接使用
this.$http.get(地址).then(function(res){ },function(err){
})
實例:
<template> <div> <h3>home組件</h3> <button @click="addList()">加載</button> <ul> <li v-for="item in list">{{item.title}}</li> </ul> </div> </template> <script> export default { name: "home", data(){ return{ list:[] } }, methods:{ addList(){ //請求數據 var api='http://www.phonegap100.com/appapi.php?a=getPortalList&catid=20&page=1'; this.$http.get(api).then((res)=>{ this.list = res.body.result; },(err)=>{ console.log(err) }) } }, mounted() { //請求數據,操作dom可在這進行 console.log('模板編譯完成4') this.addList(); }, beforeCreate() { console.log('實例剛剛被創建1') }, created() { console.log('實例已經創建完成2') }, beforeMount() { console.log('模板編譯之前3') }, beforeUpdate() { console.log('數據更新之前') }, updated() { console.log('數據更新完畢') }, beforeDestroy() {//頁面銷毀前報錯數據 console.log('實例銷毀之前') }, destroyed() { console.log('實例銷毀完成') } } </script> <style scoped> </style>
vue-resource 提供了 7 種請求 API(REST 風格):
get(url, [options]) head(url, [options]) delete(url, [options]) jsonp(url, [options]) post(url, [body], [options]) put(url, [body], [options]) patch(url, [body], [options])
axios:
1.安裝
cnpm install axios --save
2.哪里使用那里引入
<template> <div> <h3>home組件</h3> <button @click="addList()">加載</button> <ul> <li v-for="item in list">{{item.title}}</li> </ul> </div> </template> <script> import axios from 'axios' export default { name: "home", data(){ return{ list:[] } }, methods:{ addList(){ //請求數據 var api='http://www.phonegap100.com/appapi.php?a=getPortalList&catid=20&page=1'; axios.get(api).then((res)=>{ this.list = res.data.result; }).catch((err)=>{ console.log(err) }) } }, mounted() { //請求數據,操作dom可在這進行 console.log('模板編譯完成4') this.addList(); }, } </script> <style scoped> </style>
fetch:
https://github.com/camsong/fetch-jsonp
1.安裝
cnpm install fetch-jsonp --save
addList(){ var $that = this //請求數據 // //注意: 第一個.then 中獲取到的不是最終數據,而是一個中間的數據流對象; // 注意: 第一個 .then 中獲取到的數據, 是一個 Response 類型對象; // 注意: 第二個 .then 中,獲取到的才是真正的 數據; var api='http://www.phonegap100.com/appapi.php?a=getPortalList&catid=20&page=1'; fetchJsonp(api,{ method:'get' }).then(function (res) { res.json().then((json)=>{ console.log(json) $that.list = json.result; }) }).catch(function (err) { console.log('err',err) }) }