zoukankan      html  css  js  c++  java
  • 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不知道怎么获取数据做的一个简单的范例。

    今天写文章不利,快写完的时候浏览器崩溃,连历史记录都没有留下,只能从简重新写了,就写到这里吧,如有帮助您的地方,推荐一下吧!

  • 相关阅读:
    bzoj2732[HNOI2012]射箭
    poj1474 Video Surveillance
    bzoj3167[HEOI2013]SAO
    hdu2296 Ring
    bzoj2119 股市的预测
    bzoj2244[SDOI2011]拦截导弹
    bzoj3502[PA2012]Tanie Linie(最大k区间和)
    vijos1859[TJOI2014]电源插排
    比较SQL查询性能 语句
    什么是高内聚低耦合
  • 原文地址:https://www.cnblogs.com/stealth7/p/6952790.html
Copyright © 2011-2022 走看看