vue.js 三(数据交互)isomorphic-fetch
生活随笔
收集整理的這篇文章主要介紹了
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-exactrouter/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不知道怎么獲取數據做的一個簡單的范例。
今天寫文章不利,快寫完的時候瀏覽器崩潰,連歷史記錄都沒有留下,只能從簡重新寫了,就寫到這里吧,如有幫助您的地方,推薦一下吧!
轉載于:https://www.cnblogs.com/stealth7/p/6952790.html
總結
以上是生活随笔為你收集整理的vue.js 三(数据交互)isomorphic-fetch的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: How to determine wha
- 下一篇: vue.js插件使用(01) vue-r