Vue计算属性与侦听属性的应用场景

 计算属性中不能进行异步操作:

在计算属性中我们不能进行异步操作,例如:不能使用定时器、不能处理 Ajax 请求。

<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)
		}
	},
});

:在计算属性内使用异步操作会导致没有内容。

 

 侦听属性中可以进行异步操作:

在侦听属性中我们可以进行异步操作,可以使用定时器、也可以处理 Ajax 请求。

<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)
		}
	},
});

:在 Vue 中使用定时器必须使用箭头函数!因为箭头函数的指向是静态的,会继承外部 this 的指向,如果使用普通函数, this 将不会指向 Vue 实例,而是指向 window 对象。

重点总结

扫描二维码关注公众号,回复: 15910600 查看本文章

所有被 Vue 管理的函数【data 函数、computed 中的函数、watch 中的函数等】,最好写成普通函数,这样 this 的指向才是 Vue 实例 或 组件实例对象。

所有不被 Vue 管理的函数【定时器的回调函数、Ajax 的回调函数、Promise 的回调函数】,最好写成箭头函数,这样 this 的指向才是 Vue 实例 或 组件实例对象。

原创作者 :吴小糖

创作时间:2023.6.3 

猜你喜欢

转载自blog.csdn.net/xiaowude_boke/article/details/131024279