fetch + async await 使用原生JS发送网络请求

由于现在主流浏览器支持Fetch API,无需引用其他库就能实现AJAX,一行代码就搞定,可以说是非常方便了。

 1 export default {
 2   name: 'HelloWorld',
 3   data() {
 4     return {
 5       items: []
 6     }
 7   },
 8   mounted() {
 9     this.getData()
10   },
11   methods: {
12     async getData() {
13       this.items = await (await fetch('http://localhost:8081/list')).json()
14     }
15   }
16 }

 封装使用:

...
mounted() {
    api.getData().then(res => {
      this.items = res
    }).catch(err => {
      console.log(err)
    })
},
...
// src/api/index.js

const BASE_API = process.env.BASE_API export const http = (type, url, data) => { url = BASE_API + url let options = {} if (type === 'post') { options = { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ data: data }) } } else if (type === 'get') { if (data && typeof data === 'object') { const paramArray = [] Object.keys(data).forEach(key => paramArray.push(key + '=' + data[key])) if (url.indexOf('?') === -1) { url += '?' + paramArray.join('&') } else { url = '&' + paramArray.json('&') } options = { method: 'GET' } } else if (!data) { options = { method: 'GET' } } else { alert('参数有误') } } return fetch(url, options) } export const getData = async(data) => await (await http('get', '/list', data)).json()

 

浏览器支持:

 

posted @ 2018-12-04 21:37  dora_zc  阅读(3303)  评论(0编辑  收藏  举报