开发者-导航 猿导航

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
		},
	},
	watch: {
		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
		},
	},
	watch: {
		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。

EventBus 事件总线 #

在Vue中,EventBus是一种用于组件间通信的机制,特别适用于没有父子关系的组件之间的数据传递。EventBus基于发布/订阅模式,可以简化组件间的通信,解耦组件,避免复杂的依赖和生命周期问题

事件文件 utils/event-bus.js
import Vue from 'vue'
export const EventBus = new Vue()
登录页面 login.vue
import {
	EventBus
} from '@/utils/event-bus'

...省略

login(form).then((res) => {
	if (res.success) {
		const {
			app,
			token
		} = res.data;
		EventBus.$emit('user-logged-in', app); // 发布登录订阅
		this.$router.push("/");
	} else {
		this.$message.error(res.msg);
	}
});
header组件 layout/header.vue
created() {
	// 绑定事件
	EventBus.$on('user-logged-in', (user) => {
		this.userInfo = user;
	})
},
beforeDestroy() {
	// 销毁时关闭
	EventBus.$off('user-logged-in');
},