vue await fetch 使用

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/maindek/article/details/81842298

await/async 是 ES7 最重要特性之一,它是目前为止 JS 最佳的异步解决方案了。


先说一下async的用法,它作为一个关键字放到函数前面,用于表示函数是一个异步函数,因为async就是异步的意思, 异步函数也就意味着该函数的执行不会阻塞后面代码的执行。

写一个async 函数

async function timeout() {
  return 'hello world';
}

   语法很简单,就是在函数前面加上async 关键字,来表示它是异步的,那怎么调用呢?async 函数也是函数,平时我们怎么使用函数就怎么使用它,直接加括号调用就可以了,为了表示它没有阻塞它后面代码的执行,我们在async 函数调用之后加一句console.log;

async function timeout() {
    return 'hello world'
}
timeout();
console.log('虽然在后面,但是我先执行');

fetch 基本使用方法点击 这里

下边一个小例子说个基本的请求吧

<template>
  <div id="app">
    <button @click="fetchData()" >fetch 获取数据</button>
    <p>{{text}}</p>
  </div>
</template>

<script>
export default {
  name: 'app',
  data () {
    return {
      text:''
    }
  },
  methods:{
    fetchData(){
      // fetch是相对较新的技术,当然就会存在浏览器兼容性的问题,当前各个浏览器低版本的情况下都是不被支持的,因此为了在所有主流浏览器中使用fetch 需要考虑 fetch 的 polyfill 了

      async function ff(){
        let data = await fetch('../static/data.json').then(res => res.json());
        console.log(data,'data');
        return data;
      }
      ff().then(res => {
        console.log(res,'res');
        this.text = 'name:'+res.name+',age:'+res.age+'sex:'+res.sex;
      }).catch(reason => console.log(reason.message));

    }
  }
}
</script>

<style lang="scss">

</style>

猜你喜欢

转载自blog.csdn.net/maindek/article/details/81842298
今日推荐