五、Vue:使用axios庫進行get和post、用攔截器對請求和響應進行預處理、Mock(數據模擬)


一、axios

【應用】進行請求和傳表單
【axios中文檔】:https://www.kancloud.cn/yunye/axios/234845
【vue-axios】:https://cn.vuejs.org/v2/cookbook/using-axios-to-consume-apis.html
【參考】:https://blog.csdn.net/u010132177/article/details/103116767

1.1 安裝axios

進入項目目錄,運行cmd,運行如下代碼:

npm install --save axios

運行項目:

npm run dev

1.2 掛載axios到$axios寫法(get)

第一步 src/main.js

【1】引入axios為 Axios
【2】掛載Axios到 $axios (使用其內部函數時:this.$Axios即可)

// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import Axios from "axios" //【1】引入axios

Vue.prototype.$axios = Axios //【2】掛載Axios到 $axios (使用其內部函數時:this.$Axios即可)
Vue.config.productionTip = false

/* eslint-disable no-new */
new Vue({
  el: '#app', //[1]:在index.html里id為#app標簽里寫入組件內容
  components: { App },//[2]:寫入的組件
  template: '<App/>' //[3]:寫入的模板名(也可看成一個完整組件)
})

第二步 parent.vue

<template>
  <div class="parent">

    <!-- 【2】把獲取到的數據循環展現出來 -->
    <ul>
      <li v-for="v in list">{{v.title}}</li>
    </ul>

    <hr/>【顯示獲取到的請求】<hr/>
    {{list}}

  </div>
</template>

<script>
  //import axios from 'axios' //首先導入安裝好的axios

  export default{
    name:'parent',
    components:{},
    data(){
      return{
        list:[] //定義一個空數組用於存放接收到的數據
      }
    },
    //【1】生命周期函數,組件安裝好后調用此函數
    mounted (){
      let api="http://www.phonegap100.com/appapi.php?a=getPortalList&catid=20";
      this.$axios  //對應main.js里掛載寫法
      .get(api)
      .then(res=> {
        console.log(res);
        this.list=res.data.result;
      })
      .catch(error=>{
        console.log(error);
      })
    },
    filters:{},
    directives:{},

  }
</script>

<style scoped>
</style>

效果:
【國內首家】微信小程序視頻教程免費下載
ionic域資源共享 CORS 詳解
移動端觸摸滑動js插件_html5手機端輪播插件
未來程序員會被機器人取代嗎?
錘子安全錘_錘子真的出了個“錘子”:車充+安全錘
html5能做什么_html5能做哪些開發?
平安口袋銀行App采用-Cordova混合開發
JavaScript Emoji 表情庫_js 類似於qq微信的表情庫
cordova熱更新插件-不發布應用市場動態更新APP源碼
央行新規!支付寶、微信用戶別忘做這件事
HTML5 移動app開發框架該如何選擇
純CSS3動畫按鈕效果,可用於移動wap app開發
京東每天虧上億_不會抄襲、剽竊?必將死在互聯網下一站的起點上! ...
ionic react-native和native開發移動app那個好
這12行代碼分分鍾讓你電腦崩潰手機重啟
羅振宇羅永浩雷軍們的演講 你喜歡哪一個
ionic-native-transitions讓你的Ionic應用比原生還快
ionic 1.2.4 發布,最好的html5移動app開發框架
phonegap發布應用到appstore
HTML5仿蘋果應用的動畫
【顯示獲取到的請求】
[ { "aid": "499", "catid": "20", "username": "admin", "title": "【國內首家】微信小程序視頻教程免費下載", "pic": "portal/201610/13/211832yvlbybpl3rologrr.jpg", "dateline": "1476364740" }, { "aid": "498", "catid": "20", "username": "admin", "title": "ionic域資源共享 CORS 詳解", "pic": "", "dateline": "1472952906" }, { "aid": "497", "catid": "20", "username": "admin", "title": "移動端觸摸滑動js插件_html5手機端輪播插件", "pic": "portal/201606/28/211604ullzo5arr4iurnum.jpg", "dateline": "1467119820" }, { "aid": "496", "catid": "20", "username": "admin", "title": "未來程序員會被機器人取代嗎?", "pic": "portal/201606/02/221818eafffffm4srfdf4s.jpg", "dateline": "1464874140" }, { "aid": "495", "catid": "20", "username": "admin", "title": "錘子安全錘_錘子真的出了個“錘子”:車充+安全錘", "pic": "portal/201605/20/213752f6i56f1e0hbfzhkb.jpg", "dateline": "1463751505" }, { "aid": "494", "catid": "20", "username": "admin", "title": "html5能做什么_html5能做哪些開發?", "pic": "", "dateline": "1463664540" }, { "aid": "493", "catid": "20", "username": "admin", "title": "平安口袋銀行App采用-Cordova混合開發", "pic": "", "dateline": "1463294580" }, { "aid": "492", "catid": "20", "username": "admin", "title": "JavaScript Emoji 表情庫_js 類似於qq微信的表情庫", "pic": "portal/201604/25/084907r2e3im3dvd1q3f7z.jpg", "dateline": "1461545392" }, { "aid": "491", "catid": "20", "username": "admin", "title": "cordova熱更新插件-不發布應用市場動態更新APP源碼", "pic": "portal/201604/12/152638zaxz5xz3t58bfts2.png", "dateline": "1460446140" }, { "aid": "490", "catid": "20", "username": "admin", "title": "央行新規!支付寶、微信用戶別忘做這件事", "pic": "portal/201603/29/144942tcnnenueefagukfk.jpg", "dateline": "1459234206" }, { "aid": "471", "catid": "20", "username": "admin", "title": "HTML5 移動app開發框架該如何選擇", "pic": "portal/201511/15/163112q4kz6k2rgcgpi1tc.jpg", "dateline": "1457771160" }, { "aid": "488", "catid": "20", "username": "admin", "title": "純CSS3動畫按鈕效果,可用於移動wap app開發", "pic": "portal/201603/09/202742r1kngyt17na7n1nk.jpg", "dateline": "1457526780" }, { "aid": "487", "catid": "20", "username": "admin", "title": "京東每天虧上億_不會抄襲、剽竊?必將死在互聯網下一站的起點上! ...", "pic": "portal/201603/02/155825h28zxs2vsxjccv4c.jpg", "dateline": "1456905746" }, { "aid": "486", "catid": "20", "username": "admin", "title": "ionic react-native和native開發移動app那個好", "pic": "portal/201602/25/193433dtzfvlzl1oavhljy.jpg", "dateline": "1456398960" }, { "aid": "484", "catid": "20", "username": "admin", "title": "這12行代碼分分鍾讓你電腦崩潰手機重啟", "pic": "", "dateline": "1453426595" }, { "aid": "483", "catid": "20", "username": "admin", "title": "羅振宇羅永浩雷軍們的演講 你喜歡哪一個", "pic": "", "dateline": "1452226800" }, { "aid": "482", "catid": "20", "username": "admin", "title": "ionic-native-transitions讓你的Ionic應用比原生還快", "pic": "portal/201601/07/135529z4r7gwglv4rw8l74.jpeg", "dateline": "1452145500" }, { "aid": "481", "catid": "20", "username": "admin", "title": "ionic 1.2.4 發布,最好的html5移動app開發框架", "pic": "portal/201601/05/132107h9bllr7li74zoh49.jpg", "dateline": "1451971293" }, { "aid": "480", "catid": "20", "username": "admin", "title": "phonegap發布應用到appstore", "pic": "portal/201601/05/122115yhh22i77sqn2ijc6.jpg", "dateline": "1451967910" }, { "aid": "479", "catid": "20", "username": "admin", "title": "HTML5仿蘋果應用的動畫", "pic": "portal/201601/04/220252ycyddectvivr55pq.png", "dateline": "1451916189" } ]

1.3直接導入到組件axios寫法(get)

把main.js里的注釋掉

//import Axios from "axios"

//Vue.prototype.$axios = Axios

parent.vue

【0】首先導入安裝好的axios
【1】重點:生命周期函數,組件安裝好后調用此函數(真正用axios獲取數據部分)
【2】把獲取到的數據循環展現出來

<template>
  <div class="parent">

    <!-- 【2】把獲取到的數據循環展現出來 -->
    <ul>
      <li v-for="v in list">{{v.title}}</li>
    </ul>

    <hr/>【顯示獲取到的請求】<hr/>
    {{list}}

  </div>
</template>

<script>
  import axios from 'axios' //【0】首先導入安裝好的axios

  export default{
    name:'parent',
    components:{},
    data(){
      return{
        list:[] //【0.1】定義一個空數據用來存放接收到的數據
      }
    },
    //【1】生命周期函數,組件安裝好后調用此函數
    mounted (){
      let api="http://www.phonegap100.com/appapi.php?a=getPortalList&catid=20";
      axios
      .get(api)
      .then(res=> {  // 簡略寫法原:res參數省略了括號.then((res)=>{....})
        console.log(res);
        this.list=res.data.result;
      })
      .catch(error=>{
        console.log(error);
      })
    },
    filters:{},
    directives:{},

  }
</script>

<style scoped>
</style>

效果同1.2

1.3.1 把請求參數單獨提出來寫法(get)

效果同上例

parent.vue 中的請求部分,其它略過

api接口:http://www.phonegap100.com/appapi.php?a=getPortalList&catid=20

//【1】生命周期函數,組件安裝好后調用此函數
    mounted (){
      let api="http://www.phonegap100.com/appapi.php";
      let params={a:"getPortalList",catid:20} //【1】把參數提到此處
      this.$axios  
      .get(api,{params:params}) //【2】get加上參數
      .then(res=> {
        console.log(res);
        this.list=res.data.result;
      })
      .catch(error=>{
        console.log(error);
      })
    }

效果同1.2例

1.3 axios的post

1.3.1post簡單寫法

//form-data:?name=iwen&age=20
			//x-www-form-urlencoded:{name:"iwen",age:20}
			//注意:axios接受的post請求參數的格式是form-data格式
			import axios from "axios"
			import qs from "qs" //node.js的一個庫用於把post之類的參數轉換成需要的格式
			axios.post("http://www.wwtliu.com/sxtstu/blueberrypai/login.php",	qs.stringify({
				user_id:"iwen@qq.com",
					password:"iwen123",
					verification_code:"crfvw"
				}))
				.then(res => {
					console.log(res.data)
				})
				.catch(error => {
					console.log(error);
				})

1.3.2使用全局變量axios的post寫法

	axios.defaults.baseURL = 'https://api.example.com';
	axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
	axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

main.js

// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import Axios from "axios"
import qs from "qs"

Vue.prototype.$axios = Axios
Vue.prototype.HOST = '/api'

 Axios.defaults.baseURL = 'http://www.wwtliu.com'; //定義全局變量
 Axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

Vue.config.productionTip = false



/* eslint-disable no-new */
new Vue({
	el: '#app',
	template: '<App/>',
	components: {
		App
	}
})

post.js

<template>
	<div>
		post
	</div>
</template>
<script>
import qs from "qs"  //node.js的一個庫,用於對post之類的參數進行轉換成需要的類型
	
export default{
	name:"posts",
	data(){
		return{

		}
	},
	created(){
		var url = this.HOST + "/login";
		console.log(url);
		this.$axios.post(url,	{
			username:"iwen",
			password:"helloiwen"
		})
		.then(res => {
			console.log(res.data)
		})
		.catch(error => {
			console.log(error);
		})	
	}
}	

</script>
<style>
</style>

效果:將成功登錄對應網站

1.4 攔截器

【作用】:在請求或響應被 then 或 catch 處理前攔截它們。

mian.js

通過攔截器對發送之前數據處理,把格式不對的轉化成正確的,在組件中就不用再處理了。

// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import Axios from "axios"
import qs from "qs"

Vue.prototype.$axios = Axios
Vue.prototype.HOST = '/api'

// Axios.defaults.baseURL = 'http://www.wwtliu.com';
// Axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

Vue.config.productionTip = false

// 添加請求攔截器
Axios.interceptors.request.use(function(config) {

	if (config.method == "post") {//如果請求為post,則把其參數格式進行qs.stringify處理
		config.data = qs.stringify(config.data)
	}

	return config;
}, function(error) {
	// 對請求錯誤做些什么
	return Promise.reject(error);
});

// 添加響應攔截器
Axios.interceptors.response.use(function(response) {

	return response;
}, function(error) {
	// 對響應錯誤做點什么
	return Promise.reject(error);
});

/* eslint-disable no-new */
new Vue({
	el: '#app',
	template: '<App/>',
	components: {
		App
	}
})

post.vue

在全局中用攔截器處理數據,在組件中直接用即可,就不用進行處理參數,引用qs.stringfiy(注釋部分)處理了

<template>
	<div>
		post
	</div>
</template>
<script>
	
export default{
	name:"posts",
	data(){
		return{

		}
	},
	created(){
		// var url = this.HOST + "/login";
		// console.log(url);
		// this.$axios.post(url,	{
		// 	username:"iwen",
		// 	password:"helloiwen"
		// })
		// .then(res => {
		// 	console.log(res.data)
		// })
		// .catch(error => {
		// 	console.log(error);
		// })
		var url = this.HOST + "/movie/top250";
		this.$axios.get(url,{
			params:{
				count:10,
				start:0
			}
		})
		.then(res => {
			console.log(res.data)
		})
		.catch(error => {
			console.log(error);
		})
	}
}	

</script>
<style></style>

1.5 跨域解決方案

修改config index.js文件、host文件
【修改完成后,重新運行項目才會生效:(關閉cmd,重新,npm run dev)】

proxyTable: {
	            "/api": {
	                target: "http://localhost:3000",
	                changeOrigin: true,
	                pathRewrite: {
	                    '^/api': ''
	                }
	            }
	        }
	        
添加host
	    	Vue.prototype.HOST = '/api'
	【注意】:此種跨域解決方案,只能適用於測試階段,打包的時候,不會具備服務器不能跨域了,后端解決。

1.6 Mock:數據模擬

1.自己創建JSON文件。使用get請求形式訪問數據
	優點:方便,快捷
	缺點:只能存在get請求
2.項目中集成服務器,模擬各種接口
	優點:模擬真實線上環境
	缺點:增加開發成本
3.直接使用線上數據
	優點:真實
	缺點:不一定每個項目都存在
4.數據模擬庫
	www.mockjs.com
	https://github.com/nuysoft/Mock/wiki/Getting-Started


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM