Vue实现双向数据绑定的新姿势

在Vue中实现数据绑定还是相当灵活的,可以通过属性和指令两种方式来实现

先来看看第一种方式使用ref属性来来实现双向数据绑定

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>双向数据绑定</title>
		<script src="https://cdn.bootcss.com/vue/2.4.2/vue.min.js"></script>
		<style type="text/css">
			.box{
				width: 400px;
				height: 400px;
				margin: 200 auto;
				text-align: center;
				line-height: 400px;
				background-color: #eee;
			}
		</style>
	</head>
	<body>
		<div id="app">
			<h1>使用ref属性实现数据绑定</h1>
			<lable>姓名:</lable>
			 <!--只有按下enter键,才会输出内容...-->
			<input ref="name" type="text" name="" id="" value="" v-on:keyup.enter = "username()"/>
			<span>{{name}}</span>
			<lable>年龄:</lable>
			<!--按下alt+enter键,才会输出内容...-->
			<input ref="age" type="text" name="" id="" value="" v-on:keyup.alt.enter = "userage()"/>
			{{age}}
		</div>
		<script type="text/javascript">
			new Vue({
				el:'#app',
				data:{
					name:"",
					age:""
				
				},
				methods:{
					username: function(){
						console.log("username....");
						this.name = this.$refs.name.value;
					},
					userage: function(){
						console.log("userage...");
						this.age = this.$refs.age.value;
					}
				
				}
			})
		</script>
	</body>
</html>

 

接下来再看看使用v-model指令实现双向数据绑定,这中方式和angular的ng-model指令实现数据绑定如出一辙。

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>双向数据绑定</title>
		<script src="https://cdn.bootcss.com/vue/2.4.2/vue.min.js"></script>
		<style type="text/css">
			.box{
				width: 400px;
				height: 400px;
				margin: 200 auto;
				text-align: center;
				line-height: 400px;
				background-color: #eee;
			}
		</style>
	</head>
	<body>
		<div id="app">
			<h1>使用v-model实现数据绑定</h1>
			<lable>姓名:</lable>
			 <!--只有按下enter键,才会输出内容...-->
			<input ref="name" type="text" name="" id="" value="" v-model = "name"/>
			<span>{{name}}</span>
			<lable>年龄:</lable>
			<!--按下alt+enter键,才会输出内容...-->
			<input ref="age" type="text" name="" id="" value=""  v-model ="age"/>
			{{age}}
		</div>
		<script type="text/javascript">
			new Vue({
				el:'#app',
				data:{
					name:"",
					age:""
				
				},
				methods:{
				
				}
			})
		</script>
	</body>
</html>

猜你喜欢

转载自blog.csdn.net/qq_36818627/article/details/82667840