五、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
posted @ 2020-01-10 16:52  晨光曦微  阅读(1437)  评论(0编辑  收藏  举报