vue await fetch 使用

| |
[不指定 2019/08/28 13:55 | by 刘新修 ]

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

 
先说一下async的用法,它作为一个关键字放到函数前面,用于表示函数是一个异步函数,因为async就是异步的意思, 异步函数也就意味着该函数的执行不会阻塞后面代码的执行。
写一个async 函数
JavaScript代码
  1. async function timeout() {  
  2.   return 'hello world';  
  3. }  
语法很简单,就是在函数前面加上async 关键字,来表示它是异步的,那怎么调用呢?async 函数也是函数,平时我们怎么使用函数就怎么使用它,直接加括号调用就可以了,为了表示它没有阻塞它后面代码的执行,我们在async 函数调用之后加一句console.log;
 
JavaScript代码
  1. async function timeout() {  
  2.     return 'hello world'  
  3. }  
  4. timeout();  
  5. console.log('虽然在后面,但是我先执行');  

fetch 基本使用方法点击 这里

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

JavaScript代码
  1. <template>  
  2.   <div id="app">  
  3.     <button @click="fetchData()" >fetch 获取数据</button>  
  4.     <p>{{text}}</p>  
  5.   </div>  
  6. </template>  
  7.   
  8. <script>  
  9. export default {  
  10.   name: 'app',  
  11.   data () {  
  12.     return {  
  13.       text:''  
  14.     }  
  15.   },  
  16.   methods:{  
  17.     fetchData(){  
  18.       // fetch是相对较新的技术,当然就会存在浏览器兼容性的问题,当前各个浏览器低版本的情况下都是不被支持的,因此为了在所有主流浏览器中使用fetch 需要考虑 fetch 的 polyfill 了  
  19.   
  20.       async function ff(){  
  21.         let data = await fetch('../static/data.json').then(res => res.json());  
  22.         console.log(data,'data');  
  23.         return data;  
  24.       }  
  25.       ff().then(res => {  
  26.         console.log(res,'res');  
  27.         this.text = 'name:'+res.name+',age:'+res.age+'sex:'+res.sex;  
  28.       }).catch(reason => console.log(reason.message));  
  29.   
  30.     }  
  31.   }  
  32. }  
  33. </script>  
  34.   
  35. <style lang="scss">  
  36.   
  37. </style>  

 

技术分类 | 评论(0) | 引用(0) | 阅读(2316)