vue await fetch 使用
await/async 是 ES7 最重要特性之一,它是目前为止 JS 最佳的异步解决方案了。
- async function timeout() {
- return 'hello world';
- }
- 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>
vue中 fetch跨域请求
fetch 是原生javaScript提供的,它可以当作全局变量使用,挂载在window对象身上的
fetch的get请求方法
简单基本的fetch请求(get)
- <div id="app">
- <button @click="getData">get请求</button>
- </div>
- <script>
- 是原生javaScript提供的,它可以当作全局变量使用,挂载在window对象身上的
- new Vue({
- // fetch
- el:"#app",
- methods:{
- getData(){
- // var p=fetch();
- // console.log(p)//fetch方法也是promise对象
- fetch('./data/name.json')
- .then( (res) => { return res.json() } )//对fetch进行格式化,否则读取不到内容
- .then( (data) => { console.log(data)} )//拿到格式化后的数据data
- .catch(error=>console.log(error))
- },
- },
- })
注意事项:
A: fetch 的 get 请求的参数是直接连接在url上的, 我们可以使用Node.js提供的url或是qureystring模块来将
Object --> String
B: fetch 的请求返回的是Promise对象,所以我们可以使用.then().catch(),但是要记住.then()至少要写两个, 第一个then是用来格式
- 格式化处理的其他方式
- fetch('./data.json')
- .then(res=>{
- res.json() //格式化json数据
- //res.text()格式胡文本数据
- //res.blob()==格式化二进制文件==
- })
- .then( data => console.log(data))
- .catch( error => console.log( error ))
fetch的post请求方法
代码示例
- <div id="app">
- <button @click="postData">post请求</button>
- </div>
- <script>
- new Vue({
- // fetch
- el:"#app",
- methods:{
- postData(){
- fetch('http://10.31.161.60:8080',{
- method:'post',
- hearders:new Headers({
- //设置请求头,解决跨域问题
- 'Content-Type':'application/x-www-form-urlencoded'
- }),
- //解决请求数据类型限制的问题
- // body:new URLSearchParams([["a", 1],["b", 2]]).toString()
- })
- .then( res => res.text() )
- .then( data => console.log( data ))
- .catch( error => console.log( error ))
- }
- },
- })
总结
fetch要手动进行一次数据格式化,但是axios是内部进行了数据的格式化
fetch get 方法请求数据,参数要直接连接在url上
fetch 格式化数据 有三种 处理方法
.json() 格式化 json 类型数据, 将 json类型 string 转换成 json 对象
.text() 格式化文本
.blob() 格式化二进制数据
fetch 书写post请求、处理
设置请求头
通过 new URLSearchPrams 来携带参数
vue.js 跨域请求 fetch / axios
假设我们的请求地址:http://localhost/Graduation_Thesis/a.php
在vue项目下 找到 config > index.js 文件;修改 index.js 文件下的 proxyTable 对象的内容;如下
- proxyTable: {
- '/api': { // '/api'相当于代表 http://localhost/Graduation_Thesis 可自行修改名字
- target: 'http://localhost/Graduation_Thesis', //我们需要请求的主要文件夹地址
- changeOrigin: true, //是否跨域
- pathRewrite: {
- '^/api': '' //路径重写
- }
- }
- },
这样就可以跨域请求 http://localhost/Graduation_Thesis 下的文件了,而需要获取文件下的 a.php 文件 需要用 fetch/ 来做请求
fetch 请求
fetch 类似于 ajax 数据提交,但 fetch 更好
- export default {
- name: 'App',
- components: {
- appHeader:Header
- },
- created(){
- fetch('/api/a.php',{ // /api既是上面跨域定义的文件地址
- method:"post", //请求方式
- headers: { //请求头
- 'Content-Type': 'application/json',
- 'Accept': 'application/json'
- },
- body:{ //发送的请求内容
- username:'hw',
- pass:'123'
- }
- }).then(res => {
- return res.json();
- }).then(res => {
- console.log(res);
- })
- }
- }
axios 请求
首先全局安装
- npm install axios
在 mian.js 引用
- //main.js
- import axios from 'axios'
- //让 axios 可以全局使用
- Vue.prototype.$axios = axios
这样就可以开始使用了
- export default {
- name: 'App',
- components: {
- appHeader:Header
- },
- created(){
- this.$axios.post("/api/a.php",{
- username:'hw',
- pass:'1123'
- })
- .then(res =>{
- console.log(res);
- })
- }
- }
vue中http请求
前后端采用异步接口进行数据交互,传统情况下,我们采用jquery中的$.ajax()方法来进行异步请求。而在vue中我们并没有引入jquery而是采用了vue的插件vue-resource,它同样对异步请求进行了封装,方便我们同服务端进行数据交互。
1、引用及使用
- cnpm install vue-resource --save-dev
在项目根目录下/src/main.js中:
- import VueResource from 'vue-resource'
- Vue.use(VueResource)
此时在vue文件中就可以使用this.$http()进行网络请求。
2、通常在项目中是需要将http请求进行封装的。
为了封装成全局因此使用vuex。
参照 vue的一些总结 这个文章进行配置vuex
配置成功后,将main.js中的VueResource内容去掉,写在vuex中的store.js中
store.js内容如下
- import Vue from 'vue'
- import Vuex from 'vuex'
- import VueResource from 'vue-resource'
- Vue.use(Vuex)
- Vue.use(VueResource)
- export default new Vuex.Store({
- state: {
- url: 'www.baidu.com'
- },
- mutations: {
- setUrl (state, res) {
- // 该方法用来改变全局变量的值
- state.url = res
- }
- }
- })
3、在store.js中封装http请求的方法
- import Vue from 'vue'
- import Vuex from 'vuex'
- import VueResource from 'vue-resource'
- Vue.use(Vuex)
- Vue.use(VueResource)
- export default new Vuex.Store({
- state: {
- // url: 'www.baidu.com'
- },
- mutations: {
- // setUrl (state, res) {
- // // 该方法用来改变全局变量的值
- // state.url = res
- // },
- get(state, data) {
- Vue.http({
- method: 'GET',
- url: data.url,
- emulateJSON: true
- })
- .then(function (success) {
- // console.log("成功",success)
- data.success(success.body);
- }, function (error) {
- // console.log("错误",error)
- data.error(error.body);
- })
- /*
- Vue.http.get("http://test.dcsf.hebeiwanteng.com/api/common/wxParking/getNowTime")
- .then((success)=>{
- console.log("成功",success)
- })
- .catch((error)=>{
- console.log("失败",error)
- })
- */
- },
- post(state, data) {
- Vue.http({
- method: 'POST',
- url: data.url,
- params: data.data,
- emulateJSON: true
- }).then(function (success) {
- data.success(success.body);
- }, function (error) {
- data.error(error.body);
- })
- },
- delete(state, data) {
- Vue.http({
- method: 'DELETE',
- url: data.url,
- params: data.data,
- emulateJSON: true
- }).then(function (success) {
- data.success(success.body);
- }, function (error) {
- data.error(error.body);
- })
- },
- put(state, data) {
- Vue.http({
- method: 'PUT',
- url: data.url,
- params: data.data,
- emulateJSON: true
- }).then(function (success) {
- data.success(success.body);
- }, function (error) {
- data.error(error.body);
- })
- },
- }
- })
此时封装好了http请求。
在vue的文件中调用:
- <script>
- import { mapState, mapMutations } from 'vuex'
- export default {
- name: 'HelloWorld',
- data () {
- return {
- }
- },
- methods: {
- ...mapMutations(['get','post','delete','put']), //引入方法
- },
- created() {
- let _this = this;
- _this.get({
- url:"此处写请求地址",
- success(success) {
- console.log("成功",success)
- },
- error(error) {
- console.log("错误",error)
- }
- });
- }
- }
- </script>
4、注意:在store.js中使用Vue.http和在vue文件中使用this.$http是一样的。
5、该方法只验证了get请求,其它请求没有做验证。
JQ增加时间戳清除清除CSS缓存
- /****** 拼接按天时间戳的方法 ******/
- var yearStr=new Date().getFullYear();
- var dateStr=new Date().getDate();
- var monthStr=(new Date().getMonth()+1+'');
- if(monthStr.length==1){
- monthStr = '0'+monthStr;
- }
- var timeStr=yearStr+'_'+monthStr+'_'+dateStr;
- //console.log(yearStr+'_'+monthStr+'_'+dateStr);
- /****** 遍历CSS按天增加时间戳 ******/
- $("link[type='text/css']").each(function(){
- console.log($(this).attr("href"))
- $(this).attr("href",$(this).attr("href")+"?t="+timeStr);
- });