24、Vue-axios常用请求

24、Vue-axios常用请求

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>行找的皮卡丘</title>
	</head>
	<body>
		<div id="app"></div>
	</body>
	<script type="text/javascript" src="js/vue.js"></script>
	<!--导包-->
	<script type="text/javascript" src="./node_modules/axios/dist/axios.js"></script>
	<script type="text/javascript">
		Vue.prototype.$axios = axios; // 挂载到全局
		
		var App={
			data(){
				return {
					res1:'',
					res2:'',
				}
			},
			template:`
				<div>
					响应1:{{res1}}
					响应2:{{res2}}
					<button @click='senAjax'>并发请求</button>
				</div>
			`,
			methods:{
				// 基本使用
				senAjax(){
					// 请求1 get  /
					// 请求2 post /add 
					this.$axios.defaults.baseURL='http://127.0.0.1:8888';  // 配置
					
					var r1 = this.$axios.get('/');
					var r2 = this.$axios.post('/add',userId="123456"); // 请求传参
					
					this.$axios.all([r1,r2])  // 并发请求
					
					.then(this.$axios.spread((res1,res2)=>{
						// 请求全部成功
						this.res1 = res1.data;
						this.res2 = res2.data;
					}))
					// 只要有一个失败就执行
					.catch(err=>{
						console.log(err)
					})
				}
			}
		};
		
		new Vue({
			el:'#app',
			data(){
				return {
					
				}
			},
			template:`<App/>`,
			components:{
				App
			}
		});
		
		
	</script>
</html>

<!--官网:https://www.kancloud.cn/yunye/axios/234845-->

猜你喜欢

转载自blog.csdn.net/weixin_44908159/article/details/107832006