vue之資料請求方式
阿新 • • 發佈:2018-12-20
vue之資料請求方式
1. vue-resource
2.axios
3.fetch-jsonp
一、vue-resource
1. 安裝vue-resource
在專案根目錄進行安裝:cnpm install vue-resource --save
save說明:將此外掛名插入到pachage.json檔案中,別人在使用時,直接npm install,就會安裝package.json裡的所配置的軟體外掛名稱了。
2.引入vue-resource
在main.js中引入這個外掛,並使用這個外掛
import VueResource from 'vue-resource' #引入外掛,VueResource 是別名 ;vue-resource 是我們下載的外掛
Vue.use(VueResource );
#使用外掛
3.使用示例:
<template> <div> <p>vue-resource方式</p> <button @click="getData()">resource</button> <hr /> <ul> <li v-for="item in list"> {{item.title}} </li> </ul> </div> </template> <script> export default { name: "app", data() { return { 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指向 this.list = response.body.result; },function (err) { console.log(err) }) } } } </script>
結果:
二、axios
1.安裝axios
在專案根目錄進行安裝:cnpm install axios --save
2.引入axios
在哪個.vue檔案裡使用就在哪裡引入,例如我在App.vue裡使用,就在App.vue裡引入,注意要在script標籤開始處引入。
import Axios from 'axios';
3.使用示例
<template> <div> <p>vue-resource方式</p> <button @click="getData()">resource</button> <hr /> <ul> <li v-for="item in list"> {{item.title}} </li> </ul> </div> </template> <script> import Axios from 'axios'; export default { name: "app", data() { return { list:[] } }, methods:{ getData(){ //請求資料 var api = 'http://www.phonegap100.com/appapi.php?a=getPortalList&catid=20&page=1'; Axios.get(api).then((response)=> { console.log(response); this.list = response.data.result; }).catch((error)=>{ console.log(error); }) } } } </script>
結果:
三、fetch-jsonp
1.安裝
在專案根目錄進行安裝:cnpm install fetch-jsonp --save
2.引入
在哪個.vue檔案裡使用就在哪裡引入,例如我在App.vue裡使用,就在App.vue裡引入,注意要在script標籤開始處引入。
3.使用示例
<template> <div> <p>vue-resource方式</p> <button @click="getData()">resource</button> <hr /> <ul> <li v-for="item in list"> {{item.title}} </li> </ul> </div> </template> <script> import FetchJsonp from 'fetch-jsonp'; export default { name: "app", data() { return { list:[] } }, methods:{ getData(){ //請求資料 var api = 'http://www.phonegap100.com/appapi.php?a=getPortalList&catid=20&page=1'; FetchJsonp(api).then((response)=>{ return response.json() }).then((json)=>{ console.log('parsed json',json) this.list = json.result; }).catch((ex)=>{ console.log('parsing failed',ex) }) } } } </script>
結果: