第一页 1 最后页 [ 显示模式: 摘要 | 列表 ]

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>  

 

vue中 fetch跨域请求

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

 fetch 是原生javaScript提供的,它可以当作全局变量使用,挂载在window对象身上的

fetch的get请求方法

简单基本的fetch请求(get)

XML/HTML代码
  1. <div id="app">  
  2.     <button @click="getData">get请求</button>  
  3. </div>  
  4.   
  5.   
  6.   
  7. <script>  
  8. 是原生javaScript提供的,它可以当作全局变量使用,挂载在window对象身上的  
  9. new Vue({  
  10.     // fetch   
  11.     el:"#app",  
  12.     methods:{  
  13.            getData(){  
  14.         // var p=fetch();  
  15.         // console.log(p)//fetch方法也是promise对象  
  16.         fetch('./data/name.json')  
  17.         .then( (res) => {  return res.json() } )//对fetch进行格式化,否则读取不到内容  
  18.         .then( (data) => { console.log(data)} )//拿到格式化后的数据data  
  19.         .catch(error=>console.log(error))  
  20.          },  
  21.   
  22.     },  
  23. })   

注意事项:


A: fetch 的 get 请求的参数是直接连接在url上的, 我们可以使用Node.js提供的url或是qureystring模块来将

  Object --> String

B: fetch 的请求返回的是Promise对象,所以我们可以使用.then().catch(),但是要记住.then()至少要写两个, 第一个then是用来格式

XML/HTML代码
  1. 格式化处理的其他方式  
  2. fetch('./data.json')  
  3. .then(res=>{  
  4.     res.json() //格式化json数据  
  5.     //res.text()格式胡文本数据   
  6.     //res.blob()==格式化二进制文件==  
  7. })  
  8. .then( data => console.log(data))  
  9. .catch( error => console.log( error ))  

fetch的post请求方法
代码示例

XML/HTML代码
  1. <div id="app">  
  2.     <button @click="postData">post请求</button>  
  3. </div>  
  4.   
  5.   
  6. <script>  
  7. new Vue({  
  8.     // fetch   
  9.     el:"#app",  
  10.     methods:{  
  11.         postData(){  
  12.             fetch('http://10.31.161.60:8080',{  
  13.                 method:'post',  
  14.                 hearders:new Headers({  
  15.                     //设置请求头,解决跨域问题   
  16.                     'Content-Type':'application/x-www-form-urlencoded'  
  17.                 }),  
  18.                 //解决请求数据类型限制的问题  
  19.                 // body:new URLSearchParams([["a", 1],["b", 2]]).toString()  
  20.             })  
  21.             .then( res => res.text() )  
  22.             .then( data => console.log( data ))  
  23.             .catch( error => console.log( error ))  
  24.   
  25.         }  
  26.     },  
  27. })  

总结

fetch要手动进行一次数据格式化,但是axios是内部进行了数据的格式化

fetch get 方法请求数据,参数要直接连接在url上

fetch 格式化数据 有三种 处理方法

.json() 格式化 json 类型数据, 将 json类型 string 转换成 json 对象

.text() 格式化文本

.blob() 格式化二进制数据

fetch 书写post请求、处理

设置请求头

通过 new URLSearchPrams 来携带参数

vue.js 跨域请求 fetch / axios

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

 假设我们的请求地址:http://localhost/Graduation_Thesis/a.php

在vue项目下 找到  config  > index.js 文件;修改 index.js 文件下的 proxyTable 对象的内容;如下

JavaScript代码
  1. proxyTable: {  
  2.      '/api': {              //  '/api'相当于代表  http://localhost/Graduation_Thesis  可自行修改名字  
  3.        target: 'http://localhost/Graduation_Thesis', //我们需要请求的主要文件夹地址  
  4.        changeOrigin: true//是否跨域  
  5.        pathRewrite: {  
  6.          '^/api''' //路径重写  
  7.        }  
  8.      }  
  9.    },  

这样就可以跨域请求  http://localhost/Graduation_Thesis    下的文件了,而需要获取文件下的 a.php 文件 需要用 fetch/  来做请求

fetch  请求

fetch 类似于 ajax 数据提交,但 fetch 更好

JavaScript代码
  1. export default {  
  2.   name: 'App',  
  3.   components: {  
  4.     appHeader:Header  
  5.   },  
  6.   created(){  
  7.     fetch('/api/a.php',{              //  /api既是上面跨域定义的文件地址  
  8.       method:"post",                  //请求方式  
  9.       headers: {                      //请求头  
  10.         'Content-Type''application/json',  
  11.         'Accept''application/json'  
  12.       },  
  13.       body:{                          //发送的请求内容  
  14.         username:'hw',  
  15.         pass:'123'  
  16.       }  
  17.     }).then(res => {  
  18.       return res.json();  
  19.     }).then(res => {  
  20.       console.log(res);  
  21.     })  
  22.   }  
  23. }  

axios  请求

首先全局安装

JavaScript代码
  1. npm install axios  

在 mian.js 引用

JavaScript代码
  1. //main.js  
  2.    
  3. import axios from 'axios'  
  4.    
  5.    
  6. //让 axios 可以全局使用  
  7. Vue.prototype.$axios = axios  

这样就可以开始使用了

JavaScript代码
  1. export default {  
  2.   name: 'App',  
  3.   components: {  
  4.     appHeader:Header  
  5.   },  
  6.   created(){  
  7.     this.$axios.post("/api/a.php",{  
  8.       username:'hw',  
  9.       pass:'1123'  
  10.     })  
  11.       .then(res =>{  
  12.         console.log(res);  
  13.       })  
  14.   }  
  15. }  

 

vue中http请求

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

 前后端采用异步接口进行数据交互,传统情况下,我们采用jquery中的$.ajax()方法来进行异步请求。而在vue中我们并没有引入jquery而是采用了vue的插件vue-resource,它同样对异步请求进行了封装,方便我们同服务端进行数据交互。

1、引用及使用

C#代码
  1. cnpm install vue-resource --save-dev   

在项目根目录下/src/main.js中:

JavaScript代码
  1. import VueResource from 'vue-resource'  
  2. Vue.use(VueResource)  

此时在vue文件中就可以使用this.$http()进行网络请求。

2、通常在项目中是需要将http请求进行封装的。

为了封装成全局因此使用vuex。

参照 vue的一些总结 这个文章进行配置vuex

配置成功后,将main.js中的VueResource内容去掉,写在vuex中的store.js中

store.js内容如下

JavaScript代码
  1. import Vue from 'vue'  
  2. import Vuex from 'vuex'  
  3. import VueResource from 'vue-resource'  
  4. Vue.use(Vuex)  
  5. Vue.use(VueResource)  
  6. export default new Vuex.Store({  
  7.   state: {  
  8.     url: 'www.baidu.com'  
  9.   },  
  10.   mutations: {  
  11.     setUrl (state, res) {  
  12.       // 该方法用来改变全局变量的值  
  13.       state.url = res  
  14.     }  
  15.   }  
  16. })  

3、在store.js中封装http请求的方法

JavaScript代码
  1. import Vue from 'vue'  
  2. import Vuex from 'vuex'  
  3. import VueResource from 'vue-resource'  
  4. Vue.use(Vuex)  
  5. Vue.use(VueResource)  
  6. export default new Vuex.Store({  
  7.   state: {  
  8.     // url: 'www.baidu.com'  
  9.   },  
  10.   mutations: {  
  11.     // setUrl (state, res) {  
  12.     //   // 该方法用来改变全局变量的值  
  13.     //   state.url = res  
  14.     // },  
  15.     get(state, data) {  
  16.       Vue.http({  
  17.         method: 'GET',  
  18.         url: data.url,  
  19.         emulateJSON: true  
  20.       })  
  21.         .then(function (success) {  
  22.         // console.log("成功",success)  
  23.           data.success(success.body);  
  24.         }, function (error) {  
  25.         // console.log("错误",error)  
  26.           data.error(error.body);  
  27.         })  
  28.       /* 
  29.       Vue.http.get("http://test.dcsf.hebeiwanteng.com/api/common/wxParking/getNowTime") 
  30.         .then((success)=>{ 
  31.           console.log("成功",success) 
  32.         }) 
  33.         .catch((error)=>{ 
  34.           console.log("失败",error) 
  35.         }) 
  36.       */  
  37.     },  
  38.     post(state, data) {  
  39.       Vue.http({  
  40.         method: 'POST',  
  41.         url: data.url,  
  42.         params: data.data,  
  43.         emulateJSON: true  
  44.       }).then(function (success) {  
  45.           data.success(success.body);  
  46.         }, function (error) {  
  47.           data.error(error.body);  
  48.         })  
  49.     },  
  50.     delete(state, data) {  
  51.       Vue.http({  
  52.         method: 'DELETE',  
  53.         url: data.url,  
  54.         params: data.data,  
  55.         emulateJSON: true  
  56.       }).then(function (success) {  
  57.           data.success(success.body);  
  58.         }, function (error) {  
  59.           data.error(error.body);  
  60.         })  
  61.     },  
  62.     put(state, data) {  
  63.       Vue.http({  
  64.         method: 'PUT',  
  65.         url: data.url,  
  66.         params: data.data,  
  67.         emulateJSON: true  
  68.       }).then(function (success) {  
  69.           data.success(success.body);  
  70.         }, function (error) {  
  71.           data.error(error.body);  
  72.         })  
  73.     },  
  74.   }  
  75. })  

此时封装好了http请求。

 

在vue的文件中调用:

JavaScript代码
  1. <script>  
  2.   import { mapState, mapMutations } from 'vuex'  
  3.   export default {  
  4.     name: 'HelloWorld',  
  5.     data () {  
  6.       return {  
  7.       }  
  8.     },  
  9.     methods: {  
  10.       ...mapMutations(['get','post','delete','put']), //引入方法  
  11.     },  
  12.     created() {  
  13.       let _this = this;  
  14.       _this.get({  
  15.         url:"此处写请求地址",  
  16.         success(success) {  
  17.           console.log("成功",success)  
  18.         },  
  19.         error(error) {  
  20.           console.log("错误",error)  
  21.         }  
  22.       });  
  23.     }  
  24.   }  
  25. </script>  

4、注意:在store.js中使用Vue.http和在vue文件中使用this.$http是一样的。

5、该方法只验证了get请求,其它请求没有做验证。

JavaScript代码
  1. /****** 拼接按天时间戳的方法 ******/  
  2. var yearStr=new Date().getFullYear();  
  3. var dateStr=new Date().getDate();  
  4. var monthStr=(new Date().getMonth()+1+'');  
  5. if(monthStr.length==1){  
  6.     monthStr = '0'+monthStr;  
  7. }  
  8. var timeStr=yearStr+'_'+monthStr+'_'+dateStr;  
  9. //console.log(yearStr+'_'+monthStr+'_'+dateStr);  
  10.   
  11.   
  12. /****** 遍历CSS按天增加时间戳 ******/  
  13. $("link[type='text/css']").each(function(){  
  14.     console.log($(this).attr("href"))  
  15.     $(this).attr("href",$(this).attr("href")+"?t="+timeStr);  
  16. });  
 
第一页 1 最后页 [ 显示模式: 摘要 | 列表 ]