• 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()

    浏览器支持:

  • 相关阅读:
    【读书笔记】《思考,快与慢》
    【2020-12-09】别人看不上的,正是绝佳机会
    员工的重要性
    二叉树的堂兄弟节点
    占位
    数组中重复的数字
    从上到下打印二叉树
    Python生成exe
    二叉搜索树节点最小距离
    第N个斐波那契数
  • 原文地址:https://www.cnblogs.com/dora-zc/p/10067383.html
Copyright © 2020-2023  润新知