vue.js 三(数据交互)isomorphic-fetch

本文介绍了如何在Vue.js项目中使用Fetch API进行数据获取。通过一个简单的示例,展示了如何配置环境并实现数据的获取与展示。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 至于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不知道怎么获取数据做的一个简单的范例。

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

转载于:https://www.cnblogs.com/stealth7/p/6952790.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值