[Vue] basic (middle): data agent, event processing, calculation and monitoring properties, class and style binding

Posted by vigour on Mon, 13 Dec 2021 15:04:59 +0100

Welcome to learn and communicate!!!
Updating continuously

1. Data broker

Object in ES6 Defineproperty method

object. The defineproperty method is the syntax in ES6 and needs to be reviewed to better understand the data binding in Vue.

case

let number = 18
let person = {
	name:'Zhang San',
	sex:'male',
}

Object.defineProperty(person,'age',{
	// value:18,          
	//The following three items control the operation of attributes appended by this method
	// enumerable:true, / / controls whether attributes can be enumerated (i.e., traversed). The default value is false
	// writable:true, / / controls whether the attribute can be modified. The default value is false
	// configurable:true / / controls whether the attribute can be deleted. The default value is false

	//When someone reads the age attribute of person, the get function (getter) will be called, and the return value is the value of age
	get(){
		// console.log('someone read the age attribute ')
		return number
	},
				
	//When someone modifies the age attribute of person, the set function (setter) will be called and the modified specific value will be received
	set(value){
		console.log('Someone modified it age Property and the value is',value)
		number = value
	}
	// Summary: change the object attribute value by changing the number variable

})
// console.log(Object.keys(person))
console.log(person)

Data broker in Vue

Data broker: the operation (read or write) of an attribute in another object through an object broker

Case understanding:

let obj = {x:100}
let obj2 = {y:200}

// You can read and modify x through obj2
Object.defineProperty(obj2,'x',{
	get(){
		return obj.x   //When accessing X through obj2, you actually get obj x
	},
	set(value){    //If set is called, you want to change obj Value of X
		obj.x = value
	}
})

Benefits of data broker in Vue: more convenient operation of data in data

Basic principles of data broker in Vue:

  • Through object Defineproperty() adds all the properties in the data object to vm (vm is the instance of Vue object and the instance of new Vue operation).
  • Specify a getter/setter for each property added to the vm.
  • Operate (read / write) the corresponding properties in data within getter/setter.

2. Event handling

Basic use of events

  • Bind the event using v-on:xxx or @ xxx, where xxx is the event name;
  • The event callback needs to be configured in the methods object and will eventually be on the vm;
  • Do not use the arrow function for the functions configured in methods, otherwise this is not a vm;
  • The functions configured in methods are all functions managed by Vue, and this points to vm or component instance objects;
  • @click="demo" and @ click="demo" ($event) "have the same effect, but the latter can pass parameters;

Binding listening:

  • v-on:xxx="fun"
  • @xxx="fun"
  • @XXX = "fun (parameter)"
  • Default event parameter: Event
  • Implicit attribute object: $event

Event modifiers in Vue

Modifier explain
preventBlock default event (common) event.preventDefault()
stopPrevent event bubbling (common) event.stopPropagation()
onceThe event is triggered only once (common);
captureUse the capture mode of events;
selfOnly event The event is triggered only when target is the element of the current operation;
passiveThe default behavior of the event is executed immediately without waiting for the event callback to complete; (applicable to the development of mobile terminal equipment)
<!-- Prepare a container-->
<div id="root">
	<h2>welcome{{name}}classmate</h2>
	<!-- Block default events (common) -->
	<a href="http://www.baidu. Com "@click.prevent =" showinfo "> Click me for tips</a>

	<!-- Prevent event bubbling (common) -->
	<div class="demo1" @click="showInfo">
		<button @click.stop="showInfo">Click my prompt</button>
		<!-- Modifiers can be written continuously -->----------!!!!Tips!!!!! (note the order)
		<!-- <a href="http://www.baidu. Com "@click.prevent.stop =" showinfo "> click my prompt < / a > -- >
	</div>

	<!-- Event triggered only once (common) -->
	<button @click.once="showInfo">Click my prompt</button>

	<!-- Capture mode using events -->
	<div class="box1" @click.capture="showMsg(1)">
		div1
		<div class="box2" @click="showMsg(2)">
			div2
		</div>
	</div>

	<!-- only event.target The event is triggered only when it is the element of the current operation; -->
	<div class="demo1" @click.self="showInfo">
		<button @click="showInfo">Click my prompt</button>
	</div>

	<!-- The default behavior of the event is executed immediately without waiting for the event callback to complete; -->
	<!-- Example: if not.passive,In this case, 100000 counts will be completed first, and then the scroll bar operation will be performed -->
	<ul @wheel.passive="demo" class="list">
		<li>1</li>
		<li>2</li>
		<li>3</li>
		<li>4</li>
	</ul>

</div>

<script type="text/javascript">
	Vue.config.productionTip = false //Prevent vue from generating production prompts at startup.

	new Vue({
		el:'#root',
		data:{
			name:'Xiao Wang'
		},
		methods:{
			showInfo(e){
				alert('Hello, classmate!')
				// console.log(e.target)
			},
			showMsg(msg){
				console.log(msg)
			},
			demo(){
				for (let i = 0; i < 100000; i++) {
					console.log('#')
				}
				console.log('I'm dead')
			}
		}
	})
</script>

Keyboard events for Vue

1. Key aliases commonly used in Vue: (usage: @ keyup.enter="showInfo")

explainKey alias
enterenter
deleteDelete (capture delete and backspace keys)
sign outesc
Spacespace
Line feedtab (special, must be used with keydown)
upperup
lowerdown
Leftleft
rightright

2. Vue does not provide an alias key. You can use the original key value of the key to bind, but the two word key should be changed to kebab case (named by a short horizontal line), such as switching the case key caps lock

3. System modifier keys (special usage): ctrl, alt, shift, meta (i.e. windows key)

  • Use with keyup: press the modifier key, then press other keys, and then release other keys to trigger the event.
  • Use with keydown: normally trigger events.

4. You can also use keyCode to specify specific keys (not recommended, this feature has been abolished in the web standard), for example: @ keydown.13="showInfo"

5,Vue.config.keyCodes. User defined key name = key code. You can customize key alias

<!-- Prepare a container-->
<div id="root">
	<h2>welcome{{name}}classmate</h2>
	<input type="text" placeholder="Press enter to prompt for input" @keydown.huiche="showInfo">
	<!-- @keydown.ctrl.y Indicates that only press ctrl+y Key to trigger the event -->---!!!!Tips!!!
</div>

<script type="text/javascript">
	Vue.config.productionTip = false //Prevent vue from generating production prompts at startup.
	Vue.config.keyCodes.huiche = 13 //An alias key is defined

	new Vue({
		el:'#root',
		data:{
			name:'Xiao Wang'
		},
		methods: {
			showInfo(e){
				// console.log(e.key,e.keyCode) / / obtain the code of the pressed key through e.keyCode, e.key obtain the name of the key
				console.log(e.target.value)
			}
		},
	})
</script>

3. Calculation attribute

Calculate attribute: that is, the attribute to be used does not exist and must be calculated from the existing attribute.

1. Usage method: define the calculation attribute in the calculated object, and use {method name}} in the page to display the calculation results

2. Principle: the bottom layer uses objcet Getters and setter s provided by the defineproperty method.

3. Execution of get function:

  • It is executed once on the first reading.
  • When the dependent data changes, it will be called again.

4. Advantages: compared with the methods implementation, there is an internal caching mechanism (reuse), which is more efficient and convenient for debugging.
5. Note:

  • The calculated attributes will eventually appear on the vm and can be read and used directly.
  • If the calculation attribute is to be modified, the set function must be written to respond to the modification, and the data in the set will change.
<div id="root">
	Last name:<input type="text" v-model="firstName"> <br/><br/>
	Name:<input type="text" v-model="lastName"> <br/><br/>
	Full name:<span>{{fullName}}</span> <br/><br/>
	<!-- Full name:<span>{{fullName}}</span> <br/><br/>
	Full name:<span>{{fullName}}</span> <br/><br/>
	Full name:<span>{{fullName}}</span> -->    
	<!-- The above three places are called only once get(),That is, it is called for the first time, and it will be called again when the data is changed -->
</div>

<script type="text/javascript">
	Vue.config.productionTip = false //Prevent vue from generating production prompts at startup.

	const vm = new Vue({
		el:'#root',
		data:{
			firstName:'Zhang',
			lastName:'three',
			x:'Hello'
		},
		// Calculation properties
		computed:{
			fullName:{
				//Get function: when someone reads fullName, get will be called, and the return value will be used as the value of fullName
				//When is get called? 1. When reading fullName for the first time. 2. When the dependent data changes.
				get(){
					console.log('get Called')
					// console.log(this) / / this here is vm
					return this.firstName + '-' + this.lastName
				},
				//When is set called? When fullName is modified.
				set(value){   //Value refers to the modified value
					console.log('set',value)
					// If only the value value is modified but not returned to fullname, fullname cannot read the modified change
					const arr = value.split('-')
					this.firstName = arr[0]
					this.lastName = arr[1]
				}
			}
			// //Abbreviation: when the calculation attribute is read-only and not modified
			// fullName(){
			// 	console.log('get called ')
			// 	return this.firstName + '-' + this.lastName
			// }
		}
	})
</script>

4. Monitoring properties

Monitoring attribute watch:

1. When the monitored attribute changes, the callback function will be called automatically to calculate and perform relevant operations within the function
2. The monitored property must exist for monitoring
3. There are two ways to write monitoring:

  • When new Vue, pass in the watch configuration to monitor the specified properties
  • Via VM$ Watch monitoring (the monitoring object is not specified when the object is created, and can be used later when supplementary monitoring is performed)
<div id="root">
	<h2>It's a fine day today{{info}}</h2>
	<button @click="changeWeather">Switch weather</button>
</div>

<script type="text/javascript">
	Vue.config.productionTip = false //Prevent vue from generating production prompts at startup.
		
	const vm = new Vue({
		el:'#root',
		data:{
			isHot:true,
		},
		computed:{
			info(){
				return this.isHot ? 'scorching hot' : 'pleasantly cool'
		}
		},
		methods: {
			changeWeather(){
				this.isHot = !this.isHot
			}
		},
		watch:{
			isHot:{
				//immediate:true, / / let the handler call during initialization
				//When does the handler call? When isHot changes.
				handler(newValue,oldValue){
					console.log('isHot It was modified',newValue,oldValue) //New value after change and value before change
				}
			}
		}
	})

//The second method: (premise: create an instance first)
	vm.$watch('isHot',{
	immediate:true, //Let the handler call during initialization
	//When does the handler call? When isHot changes.
	handler(newValue,oldValue){
		console.log('isHot It was modified',newValue,oldValue)
		}
	})
</script>

Depth monitoring

  • By default, the watch in Vue does not monitor the change of the internal value of the object (only one layer is viewed by default).
  • Configure deep:true in watch to monitor the changes of internal values of objects (multiple layers can be viewed by default).

remarks:

  • Vue can monitor the changes of internal values of objects, but the watch provided by Vue cannot be used by default!!
  • When using watch, decide whether to use deep monitoring according to the specific structure of the data.
<h3>a The value of is:{{numbers.a}}</h3>
<button @click="numbers.a++">Let me a+1</button>

<script type="text/javascript">
	Vue.config.productionTip = false //Prevent vue from generating production prompts at startup.
		
	const vm = new Vue({
		el:'#root',
		data:{
			numbers:{
				a:1,
				b:1,
				c:{
					d:{
						e:100
					}
				}
			}
		},
		watch:{
			//Monitor the change of an attribute in the multi-level structure
			/* 'numbers.a':{       //That is, restore the original writing method and add '', otherwise an illegal string will be reported
				handler(){
					console.log('a Changed ')
				}
			} */
			//Monitor the changes of all attributes in the multi-level structure
			numbers:{
				deep:true,
				handler(){
					console.log('numbers Changed')
				}
			}
		}
	})
</script>

Abbreviations for monitoring properties

watch:{
		//Normal writing
	isHot:{
		// immediate:true, / / let the handler call during initialization
		// deep:true, / / deep monitoring
		handler(newValue,oldValue){
			console.log('isHot It was modified',newValue,oldValue)
		}
	}, */
		//Abbreviation (premise: it can be used when the configuration items such as immediate and deep are not required, that is, when the handler is behind the configuration item)
	isHot(newValue,oldValue){
		console.log('isHot It was modified',newValue,oldValue,this)
	} 
}

//Normal writing
vm.$watch('isHot',{
	immediate:true, //Let the handler call during initialization
	deep:true,//Depth monitoring
	handler(newValue,oldValue){
		console.log('isHot It was modified',newValue,oldValue)
	}
}) 

//Abbreviation
vm.$watch('isHot',function(newValue,oldValue){   //Note: the arrow function cannot be used here, which will cause this to point to windows
	console.log('isHot It was modified',newValue,oldValue)
}) 

Comparison of calculated and monitored attributes:

Difference between computed and watch:

  1. The functions that can be completed by computed and watch can be completed.
  2. The functions that can be completed by watch may not be completed by computed. For example, watch can perform asynchronous operations. Because the result of watch is not based on the return value, but modified by writing code, but calculated is based on the return value.

Two important small principles:

  • The functions managed by Vue should be written as ordinary functions, so that the point of this is the vm or component instance object.
  • All functions not managed by Vue (timer callback function, ajax callback function, Promise callback function, etc.) should be written as arrow function, so that the point of this is the vm or component instance object.

5. class and style binding

class style:

  • Writing method: class="xxx" xxx can be string, object or array.
  • The string writing method is applicable to: if the class name is uncertain, it should be obtained dynamically.
  • Object writing is applicable to binding multiple styles. The number and name are uncertain.
  • The array writing method is applicable to: to bind multiple styles, the number and name are determined, but it is uncertain whether to use them.

style:

  • : style="{fontSize: xxx}" where xxx is a dynamic value.
  • : style="[a,b]" where a and B are style objects.

Topics: Javascript Front-end Vue.js