vue請求數據的三種方式


  • vue-resource 官方提供的 vue的一個插件
  • axios
  • fetch-jsonp

一,vue-resource請求數據

介紹:vue-resource請求數據方式是官方提供的一個插件

使用步驟:

1、安裝vue-resource模塊

1
cnpm install vue-resource --save

加--save是為了在package.json中引用,表示在生產環境中使用。因為我們在日常開發中,如果我們要打包代碼給其他人或者上傳到github,又或者要發布代碼時,package.json就是安裝所需要的包。如果只在開發環境中使用,則只需要--save-dev,有一些只在開發環境中用,有一些要在生產環境中用。

2、在 main.js 引入 vue-resource

1
2
import VueResource from 'vue-resource' ;
Vue.use(VueResource);

3、在組件里面直接使用

1
2
3
this .$http.get(地址).then( function (){
 
})

注意:this.$http.get()等等的各種http請求都是繼承promise的。promise是異步的請求;其次,.then箭頭函數里的this代表的是上下文。根據箭頭函數this的定義,只在函數定義時就已經賦值可知,this,指代的是定義函數的對象,在vue中對象就是methods當前頁面。所以this指導的是data里面的數據。如果想要獲取包裹函數外函數的數據,即閉包的概念。實現方法就是在外層函數加一個var that =  this;將外層的this先儲存到that中。

實例:

Info.vue

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
<template>
   <div id= "info" >
     <button @click= "getData" >獲取數據</button>
     <ul>
       <li v- for = "(item,index) in list" v-bind:key= "index" >
         {{item.title}}
       </li>
     </ul>
   </div>
</template>
 
<script>
   export default {
     name: "Info" ,
     data() {
       return {
         list: []
       }
     },
     methods: {
       getData: function () {
         //此處推薦使用箭頭函數。
         this .$http.get(api).then((res)=>{
           this .list = res.body.result;
         }, (err)=>{
           console.log(err);
         });
       }
     },
     mounted() {
       this .getData();
     }
   }
</script>

如果getData()中不適用箭頭函數,就需要注意this問題。

1
2
3
4
5
6
7
8
9
getData: function () {
   const _this = this ;
   this .$http.get(api).then( function (res) {
     _this.list = res.body.result;
   }, function (err) {
     console.log(err);
   });
}

二,axios請求數據

介紹:這是一個第三方的插件 github地址:https://github.com/axios/axios

axios 與 fetch-jsonp 同為第三方插件

1、安裝

1
cnpm install axios --save

直接調用。和vue-resource的區別是:aixos是每在一個頁面用一次就要在該頁面調用一次。vue-resource是綁定了全局的了。

2、哪里用哪里引入axios

1
2
3
4
5
Axios.get(api).then((response)=>{
   this .list=response.data.result;
}). catch ((error)=>{
   console.log(error);
})

關於axios的跨域請求

在config->index.js->proxyTable配置如下:target填寫自己想要的地址

如下配置,url為地址后面所帶的參數,配置好后,現在npm run dev 運行就行。

關於多個並發請求:

上面這個是同一地址的跨域,如果要拿不同地址的跨域,只需要更改config->index.js->proxyTable的配置,增加地址塊就行。

三,關於fetch-jsonp

github地址:https://github.com/camsong/fetch-jsonp

1、安裝

1
cnpm install fetch-jsonp --save

2、哪里用哪里引入fetch-jsonp

1
2
3
4
5
6
7
8
fetchJsonp( '/users.jsonp' )
  .then( function (response) {
   return response.json()
  }).then( function (json) {
   console.log( 'parsed json' , json)
  }). catch ( function (ex) {
   console.log( 'parsing failed' , ex)
  })


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM