Vue.js交互

Vue.js交互
vue,js交互需要使用vue-resource.js库
vue.js交互借助于$http完成
语法:使用promise语法

常用的交互类型

  1. get类型
  2. post类型
  3. jsonp类型

举例应用
get类型
语法:this.$http.get(‘url’, {params:{a:1,b:2…}}).then(function(res){处理请求成功},function(res){处理请求失败});

sub.php代码

<?php 
	echo $_REQUEST['a']-$_REQUEST['b'];

get.html代码

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<script type="text/javascript" src="vue.js"></script>
	<script type="text/javascript" src="vue-resource.js"></script>
</head>
<body>
	<div id="box">		
		<p>{{ arr }}</p>
		<button @click='sub()'>SUB</button>
	</div>
</body>
</html>
<script type="text/javascript">
	var vm = new Vue({
		el: '#box',
		data: {
			arr:'苟利国家生死以'	
		},
		methods: {
			sub: function(){
				this.$http.get('sub.php',{params: {a:3, b:2}}).then(
					function (res){
						this.arr = res.data;
			 		},
			 		function (res){
			 			this.arr = '请求失败';
					});
			}
		}
	});
</script>

post类型
语法:this.$http.get(‘url’,{a:1,b:2…},{emulateJSON:true}).then(function(res){处理请求成功},function(res){处理请求失败});

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<script type="text/javascript" src="vue.js"></script>
	<script type="text/javascript" src="vue-resource.js"></script>
</head>
<body>
	<div id="box">		
		<p>{{ arr }}</p>
		<button @click='sub()'>SUB</button>
	</div>
</body>
</html>
<script type="text/javascript">
	var vm = new Vue({
		el: '#box',
		data: {
			arr:'苟利国家生死以'	
		},
		methods: {
			sub: function(){
				this.$http.post('sub.php',{a:3, b:2},{emulateJSON:true}).then(
					function (res){
						this.arr = res.data;
			 		},
			 		function (res){
			 			this.arr = '请求失败';
					});
			}
		}
	});
</script>

jsonp类型
语法:this.$http.jsonp(‘url’,{params:{a:1,b:2…}},{emulateJSON:true}).then(function(res){处理请求成功},function(res){处理请求失败});

交互练习地址:https://blog.csdn.net/qq_39383675/article/category/8256374

猜你喜欢

转载自blog.csdn.net/qq_39383675/article/details/83449241
今日推荐