开发者-导航 猿导航

Vue2 笔记

发布时间:

watch 监听组件 prop 参数变化 #

基础版本 #

组件创建时,不会触发 watch 中的监听函数,下次 props 参数变化会触发 watch 中函数。

export default {
	name: "message",
	props: {
		user: { // 用户 id
			type: String
		},
		apiKey: { // API Key
			type: String
		},
	},
	watch: {
		apiKey(newVal, oldVal) {
			console.log('apiKey newVal', newVal, "apiKey oldVal:", oldVal);
		},
		user(newVal, oldVal) {
			console.log('usern ewVal', newVal, "user oldVal:", oldVal);
		}
	}
}

进阶版 #

马上会调用 watch 中的函数

export default {
	name: "message",
	props: {
		user: { // 用户 id
			type: String
		},
		apiKey: { // API Key
			type: String
		},
	},
	apiKey: {
		handler(newVal, oldVal) {
			console.log('apiKey newVal', newVal, "apiKey oldVal:", oldVal);
		},
		immediate: true 
	},
	user: {
		handler(newVal, oldVal) {
			console.log('user newVal', newVal, "user oldVal:", oldVal);
		},
		immediate: true
	}
}

高级版 #

马上会调用 watch 中的函数

export default {
	name: "message",
	props: {
		user: { // 用户 id
			type: String
		},
		apiKey: { // API Key
			type: String
		},
	},
	apiKey: {
		handler(newVal, oldVal) {
			console.log('usernewVal', newVal, "useroldVal:", oldVal);
		},
		deep: true 
	},
	user: {
		handler(newVal, oldVal) {
			console.log('usernewVal', newVal, "useroldVal:", oldVal);
		},
		deep: true 
	}
}
警告

注意,不应该使用箭头函数来定义 watcher 函数 (例如 searchQuery: newValue => this.updateAutocomplete(newValue))。

理由是箭头函数绑定了父级作用域的上下文,所以 this 将不会按照期望指向 Vue 实例,this.updateAutocomplete 将是 undefined。