Two way binding principle of VUE and its application

Keywords: Front-end Vue IE

vue implements data hijacking through Object.defineProperty(). It mainly uses its set and get properties. If you are not familiar with it, Please click here for more usage.

You can see how to use it clearly in the following examples:

<!DOCTYPE html>
<html lang="en">

<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<meta http-equiv="X-UA-Compatible" content="ie=edge">
	<title>VUE Bidirectional binding</title>
</head>

<body>
	//Name: < input type = "text" name = "" id = "" V-model = "name" placeholder = "name" >
	//Name: < input type = "text" name = "" id = "" V-model = "name" placeholder = "name" disabled >
	<p>name: <span v-text="name"></span></p>
	//Gender: < select name = "" id = "" V-model = "sex" >
		<option value="male">male</option>
		<option value="female">female</option>
	</select>
	<p>Gender: <span v-text="sex"></span></p>
	<script>
		class Vue {
			constructor(opt) {
				let data = opt.data || {},
					keys = Object.keys(data),//Get all properties of the incoming data
					_this = this;
				this.data = {};
				//Add listening property of this.data
				keys.forEach(item => {
					Object.defineProperty(this.data, item, {
						//The function triggered by reading the value of name property
						get: function () {
							return this[`_${item}`];
						},
						//The function triggered by setting the value of name property
						set: function (value) {
							this[`_${item}`] = value;
							_this.render(item);
						}
					});
				});
				//Set property value for this.data
				for (let item in data) {
					this.data[item] = data[item];
					//Trigger set function here
				}
				this.input();
			}
			//Set the display of data
			render(prot) {
				document.querySelectorAll(`[v-model=${prot}]`).forEach(el => {
					el.value = this.data[prot];//Start get function here
				});
				document.querySelectorAll(`[v-text=${prot}]`).forEach(el => {
					el.innerText = this.data[prot];//Start get function here
				});
			}
			//Input listening to text box
			input() {
				document.querySelectorAll(`[v-model]`).forEach(el => {
					el.oninput = () => {
						this.data[el.getAttribute('v-model')] = el.value;//Trigger set function here
					};
				});
			}
		}
		//Create Vue instance
		const vm = new Vue({
			data: {
				name: 'Zhang San',
				sex: 'male'
			}
		})
	</script>
</body>

</html>

It simply implements the data bidirectional binding of Vue. Of course, the v-model in it is different from the implementation principle in Vue, just to achieve the function of v-model.

If you want to know the principle of v-model in vue, please Jump to v-model details

Posted by tjohnson_nb on Sat, 30 Nov 2019 16:41:27 -0800