vue series (5) two-way data binding

You can use the v-model command in the form <input>, <textarea> and <select> to create a two-way data binding on the element. It automatically selects the correct method to update the control type elements. While some magic, but the v-model is essentially just syntax sugar. It is responsible for monitoring the user's input event to update the data, and some extreme scenarios do some special treatment.

v-model ignores value, checked, all the initial values ​​of selected characteristics to form elements of data Vue but always as an example of the data source. You should declare the initial value of the option component of the data via JavaScript.

example:

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Vue.js</title>
	<script src="https://cdn.jsdelivr.net/npm/vue"></script>
	<link rel="stylesheet" type="text/css" href="style.css">
	
</head>
<body>
	<div id="app">
         <!--第一种方法是使用ref进行的双向绑定,利用了$refs获取value值进行绑定-->
		<h1>双向数据绑定: input,select,textarea</h1>
		<label>姓名:</label>
		<input type="text" ref="name" v-on:keyup="logName">
		<span>{{name}}</span>
		<label>年龄:</label>
		<input type="text" ref="age" v-on:keyup="logAge">
		<span>{{age}}</span>
        <!--第二种则直接进行的双向绑定,使用了vue提供的v-model指令-->
		<h1>另一种双向数据绑定</h1>
		<label>姓名:</label>
		<input type="text" v-model="name2">
		<span>{{name2}}</span>
	<script type="text/javascript" src="app.js"></script>
</body>
</html>

app.js

new Vue({
	el: '#app',
	data: {
		name: '',
		name2: '',
		age: ''
	},
	methods: {
		logName: function() {
			this.name = this.$refs.name.value;
		},
		logAge: function() {
			this.age = this.$refs.age.value;
		}
	}
});

 

Guess you like

Origin blog.csdn.net/jsqfengbao/article/details/94740181