vue.js 三(數據交互)isomorphic-fetch


 至於fetch的介紹,在這里就不多說了,官方和網絡上的說明不少

之前使用jquery的Ajax朋友,可以嘗試一下使用一下這個新的api

推薦使用isomorphic-fetch,兼容Node.js和瀏覽器兩種環境運行。

npm install --save isomorphic-fetch es6-promise

這里我按照官方網站的介紹,具體在vue.js中寫了一個范例,只需要拷貝代碼到新的文件Index.vue就可以試一試看看了

<template>
  <div class="index">
    <div v-for="item in items" class="story">
      <div>{{item.title}}</div>
      <div class="story-author">{{item.author}}</div>
      <div>{{item.date}}</div>
  
      <div v-html="item.body"></div>
    </div>
  </div>
</template>

<script>



require('es6-promise').polyfill();
require('isomorphic-fetch');


export default {
  name: 'hello',
  data() {
    return {
      msg: 'Welcome to Your Vue.js App',
      items: []

    }
  }, created: function () {
    let vueThis = this;

    fetch('http://offline-news-api.herokuapp.com/stories')
      .then(function (response) {
        if (response.status >= 400) {
          throw new Error("Bad response from server");
        }
        return response.json();
      })
      .then(function (stories) {
        console.log(stories);
        vueThis.items = stories;

      });
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.story {
  border: 1px solid #ccc;
  padding: 5px;
}

.story-author {
  font-weight: bold;
  font-size: 18px;
  font-style: italic;
}
</style>

由於IE對Promise的不支持,所以還需要使用 promise-polyfill

npm install promise-polyfill --save-exact

router/index.js文件添加引用(紅色標記的地方)

import Vue from 'vue'
import Router from 'vue-router'
import Promise from 'promise-polyfill' if (!window.Promise) { window.Promise = Promise; } 

const Hello = r => require.ensure([], () => r(require('../pages/Hello')), 'group-b')
const Index = r => require.ensure([], () => r(require('../pages/Index')), 'group-a')

Vue.use(Router)

export default new Router({
  routes: [
    { path: '/', name: 'Index', component: Index },
    { path: '/hello', name: 'Hello', component: Hello }
  ]
})

由於我的瀏覽器是IE11,修改文檔模式的情況下,只有IE9+以上運行正常,IE的其他瀏覽器有要求的請慎用。

以上只是GET獲取數據的范例,其他的修改Header,跨域等一些常見問題,按照fetch對應的用法使用就可以了

這里只是對於初次使用vue.js不知道怎么獲取數據做的一個簡單的范例。

今天寫文章不利,快寫完的時候瀏覽器崩潰,連歷史記錄都沒有留下,只能從簡重新寫了,就寫到這里吧,如有幫助您的地方,推薦一下吧!


免責聲明!

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



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