1 自定义事件
vue也实现了观察者模式,提供了订阅消息,发布消息,注销消息等方法$on(type, fn) 订阅消息方法type:消息名称, fn:消息回调函数,参数是由$emit方法传递的$emit(type, ...args) 发布消息方法type:消息名称 ...args:从第二个参数开始,表示传递的数据$off(type, fn) 注销消息方法type:消息名称 fn:消息回调函数组件是一个完整独立的个体,因此彼此之间数据不会共享,所以发布消息与订阅消息必须是同一个组件
// 创建完成created() {
// 订阅消息this.$on('demo', (...args) => {
console.log(args); // 接收到参数并且打印出来})// 发送消息this.$emit('demo', 100, 200, true)}
2 $on源码
// 将事件名和函数一一对应,相当于一个典型的发布订阅
Vue.prototype.$on = function (event, fn) {
var vm = this;// 如果event事件是一个数组的话,就遍历数组,递归调用$on方法存入事件if (Array.isArray(event)) {
for (var i = 0, l = event.length; i < l; i++) {
vm.$on(event[i], fn);}} else {
// 如果是单个事件,就直接存入(vm._events[event] || (vm._events[event] = [])).push(fn);// optimize hook:event cost by using a boolean flag marked at registration// instead of a hash lookupif (hookRE.test(event)) {
vm._hasHookEvent = true;}}return vm};
3 $emit源码
Vue.prototype.$emit = function (event) {
var vm = this;{
var lowerCaseEvent = event.toLowerCase();if (lowerCaseEvent !== event && vm._events[lowerCaseEvent]) {
tip("Event \"" + lowerCaseEvent + "\" is emitted in component " +(formatComponentName(vm)) + " but the handler is registered for \"" + event + "\". " +"Note that HTML attributes are case-insensitive and you cannot use " +"v-on to listen to camelCase events when using in-DOM templates. " +"You should probably use \"" + (hyphenate(event)) + "\" instead of \"" + event + "\".");}}var cbs = vm._events[event]; // 通过事件名找到回调,并让回调函数一次执行if (cbs) {
cbs = cbs.length > 1 ? toArray(cbs) : cbs;var args = toArray(arguments, 1);var info = "event handler for \"" + event + "\"";for (var i = 0, l = cbs.length; i < l; i++) {
invokeWithErrorHandling(cbs[i], vm, args, vm, info);}}return vm};
4 我们在组件绑定事件就是通过 o n 和 on和 on和emit实现
<my-component @my-event="fn"></my-component>@my-event="fn这样的写法,会被转化成$on绑定my-event
然后就可以通过$emit触发my-event事件