Application scenarios of Vue computed properties and listening properties

 Computed properties cannot perform asynchronous operations:

We cannot perform asynchronous operations in computed properties, for example: cannot use timers, cannot handle Ajax requests.

<div id="APP">
	姓:<input type="text" v-model="firstName"> <br/><br/>
	名:<input type="text" v-model="lastName"> <br/><br/>
	全名: <span>{
   
   {fullName}}</span>
</div>
const vm = new Vue({
	el: "#APP",
	data(){
		return {
			firstName: "张",
			lastName: "三"
		}
	},
	computed:{
		fullName(){
			setTimeout(() => {
				return this.firstName + '-' + this.lastName;
			},1000)
		}
	},
});

Note : Using an asynchronous operation inside a computed property will result in no content.

 

 Asynchronous operations can be performed in the listening property:

In the listening attribute, we can perform asynchronous operations, use timers, and handle Ajax requests.

<div id="APP">
	姓:<input type="text" v-model="firstName"> <br/><br/>
	名:<input type="text" v-model="lastName"> <br/><br/>
	全名: <span>{
   
   {fullName}}</span>
</div>
const vm = new Vue({
	el: "#APP",
	data(){
		return {
			firstName: "张",
			lastName: "三",
			fullName: "张-三"
		}
	},
	watch:{
		firstName(newValue){
			setTimeout(() => {
				this.fullName = newValue + '-' + this.lastName;
			},1000)
		},
		lastName(newValue){
			setTimeout(() => {
				console.log(this); // Vue
				this.fullName = this.firstName + '-' + newValue;
			},1000)
			// 这里不能使用普通函数,普通函数的 this 指向 window
			setTimeout(function(){
				console.log(this); // window
			},1000)
		}
	},
});

Note : Arrow functions must be used to use timers in Vue! Because the pointer of the arrow function is static, it will inherit the pointer of the external this. If you use a normal function, this will not point to the Vue instance, but to the window object.

 

Key summary :

All functions managed by Vue (data function, functions in computed, functions in watch, etc.) are best written as ordinary functions, so that the point of this is the Vue instance or component instance object.

All functions not managed by Vue [timer callback function, Ajax callback function, Promise callback function] are best written as arrow functions, so that the point of this is the Vue instance or component instance object.

Original author: Wu Xiaotang

Creation time: 2023.6.3 

Guess you like

Origin blog.csdn.net/xiaowude_boke/article/details/131024279