DIV CSS 佈局教程網

Vue 資料互動實作:用 vue-resource 處理 ajax 與 jsonp
編輯:關於JavaScript     

Vue 中的非同步資料請求

Vue 本身只專注在視圖層,並沒有內建 ajax 或 jsonp 這類資料互動的能力。要在 Vue 專案裡向伺服器取資料,需要搭配 vue-resource 這個套件。

專案網址:https://github.com/pagekit/vue-resource/blob/master/README.md

基本 GET 請求

引入 vue.js 與 vue-resource.js 之後,就能透過 this.$http 發出請求:

<meta charset="UTF-8">
<title>Document</title>
<script type="text/javascript" src="vue.js"></script>
<script type="text/javascript" src="vue-resource.js"></script>
<style type="text/css">
</style>
</head>
<body>
<div id="app">
  <button @click="get()">按鈕</button>
</div>
<script type="text/javascript">
  var vm = new Vue({
    el: '#app',
    data: {},
    methods: {
      get: function () {
        this.$http.get('a.txt').then(function (res) {
          alert(res.data);
        }, function (res) {
          alert(res.data);
        });
      }
    }
  });
</script>
</body>

$http 的用法與熟悉的 ajax 相當接近,除了 this.$http.get 之外還有 this.$http.post。若要跨域抓資料,則可以改用 jsonp。

jsonp 跨域取資料

<div id="app">
  <button @click="get()">按鈕</button>
</div>
<script type="text/javascript">
  var vm = new Vue({
    el: '#app',
    data: {},
    methods: {
      get: function () {
        this.$http.jsonp('https://sug.so.360.cn/suggest', { word: 'b' }).then(function (res) {
          alert(res.data.s);
        }, function (res) {
          alert(res.status);
        });
      }
    }
  });
</script>
</body>

綜合範例:百度下拉建議

把 jsonp 與鍵盤事件結合,就能做出一個即時搜尋建議:

<meta charset="UTF-8">
<title>Document</title>
<script type="text/javascript" src="vue.js"></script>
<script type="text/javascript" src="vue-resource.js"></script>
<style type="text/css">
  * { margin: 0; padding: 0; }
  .bg { width: 200px; line-height: 30px; }
</style>
</head>
<body>
<div id="app">
  <input type="text" v-model="t"
         @keyup="get($event)"
         @keydown.down="changeDown()"
         @keyup.up.prevent="changeUp()" />
  <ul>
    <li v-for="val in arr" class="bg">{{val}}</li>
  </ul>
  <p v-show="arr.length == 0">暫無數據</p>
</div>
<script type="text/javascript">
  var vm = new Vue({
    el: '#app',
    data: {
      arr: [],
      t: '',
      iNow: -1
    },
    methods: {
      get: function (ev) {
        // 上下鍵只用來切換選項,不發請求
        if (ev.keyCode == 38 || ev.keyCode == 40) { return; }

        // 回車直接開啟搜尋
        if (ev.keyCode == 13) {
          window.open('https://www.baidu.com/s?wd=' + this.t);
          this.t = '';
        }

        this.$http.jsonp(
          'https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su',
          { wd: this.t },
          { jsonp: 'cb' }
        ).then(function (res) {
          this.arr = res.data.s;
        }, function (res) {
          alert('失敗');
        });
      },
      changeDown: function () {
        this.iNow++;
        if (this.iNow == this.arr.length) { this.iNow = -1; }
        this.t = this.arr[this.iNow];
      },
      changeUp: function () {
        this.iNow--;
        if (this.iNow == -2) { this.iNow = this.arr.length - 1; }
        this.t = this.arr[this.iNow];
      }
    }
  });
</script>
</body>

幾個實務提醒

第三個參數 { jsonp: 'cb' } 指定的是回呼函式的查詢參數名稱。不同服務商用的名字不同,百度這組介面用的是 cb,360 的建議介面則多為 callback,寫錯就會拿不到資料。

另外要留意 this 的指向。then 的第一個回呼是在 Promise 鏈中執行的,範例之所以能直接寫 this.arr = ...,是因為 vue-resource 會保留原本的 this;若換成原生 fetch 搭配箭頭函式以外的寫法,this 就會指向別的物件,需要事先用變數快取 vm 參照。

最後,vue-resource 已不再由官方維護,新專案建議改用 axios 或原生 fetch,並搭配 Vue 的元件生命週期處理請求與取消。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved