您的位置:首页 > 产品设计 > UI/UE

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

2017-06-06 17:45 591 查看
至于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不知道怎么获取数据做的一个简单的范例。

今天写文章不利,快写完的时候浏览器崩溃,连历史记录都没有留下,只能从简重新写了,就写到这里吧,如有帮助您的地方,推荐一下吧!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: