Vue3的事件綁定的實現(xiàn)邏輯是什么

Vue的事件綁定主要是通過v-on指令來實現(xiàn)的,這個指令既可以實現(xiàn)原生事件綁定,例如onclick等。也可以實現(xiàn)組件的自定義事件,從而實現(xiàn)組件的數(shù)據(jù)通信。

本文我們就來分析下Vue的事件處理的邏輯。

v-on作用于普通元素

用在普通元素上時,只能監(jiān)聽原生 DOM 事件,最多的就是onclick事件了。我們就以onclick事件來分析原理。

案例
let click = () => {
  console.log("點擊我,很快樂")
};

<!-- template -->
<div v-on:click="click">點擊我吧</div>
分析實現(xiàn)邏輯
  • 我們先來看下渲染函數(shù)
const _hoisted_1 = ["onClick"]

function render(_ctx, _cache) {
  with (_ctx) {
    const { openBlock: _openBlock, createElementBlock: _createElementBlock } = _Vue

    return (_openBlock(), _createElementBlock("div", { onClick: click }, "點擊我吧", 8 /* PROPS */, _hoisted_1))
  }
}

我們看到 渲染函數(shù)在創(chuàng)建VNode的時候傳了一個onClickpros;

  • 我們先來看下patchProp函數(shù)中對onClick這個pros的處理邏輯
export const patchProp: DOMRendererOptions['patchProp'] = (
  el,
  key,
  prevValue,
  nextValue,
  isSVG = false,
  prevChildren,
  parentComponent,
  parentSuspense,
  unmountChildren
) => {
  if (isOn(key)) {
    patchEvent(el, key, prevValue, nextValue, parentComponent)
  }
}

function patchEvent(el, rawName, prevValue, nextValue, instance = null) {
  // vei = vue event invokers
  const invokers = el._vei || (el._vei = {});
  
  if (添加) {
    const invoker = (invokers[rawName] = createInvoker(nextValue, instance));
    el.addEventListener(event, handler, options)
  } else {
    el.removeEventListener(event, handler, options)
  }
}

我們可以看出來底層就是調(diào)用的addEventListener函數(shù)進行事件監(jiān)聽綁定,調(diào)用removeEventListener進行事件監(jiān)聽解綁。其實這個實現(xiàn)邏輯很容易想到,沒什么難度。

重點分析---事件修飾符
  • once,capturepassive

這兩個可以直接作為addEventListenerremoveEventListener 的第三個參數(shù)options 中的值,因為這是W3C支持的事件可選參數(shù)。

  • stop, prevent,capture, self等。

這類修飾符被封裝在另外一個withModifiers函數(shù)中。

export const withModifiers = (fn: Function, modifiers: string[]) => {
  return (event: Event, ...args: unknown[]) => {
    for (let i = 0; i < modifiers.length; i++) {
      const guard = modifierGuards[modifiers[i]]
      if (guard && guard(event, modifiers)) return
    }
    return fn(event, ...args)
  }
}

這里設(shè)計的非常精妙,每個修飾符都對應(yīng)一個執(zhí)行函數(shù),如果調(diào)用執(zhí)行函數(shù)guard(event, modifiers)返回true, 則函數(shù)withModifiers就直接返回了,不會再執(zhí)行事件的函數(shù)fn(event, ...args)了。

這里列一些這些修飾符對應(yīng)的函數(shù):

const modifierGuards: Record<
  string,
  (e: Event, modifiers: string[]) => void | boolean
> = {
  stop: e => e.stopPropagation(),
  prevent: e => e.preventDefault(),
  self: e => e.target !== e.currentTarget,
  ctrl: e => !(e as KeyedEvent).ctrlKey,
  shift: e => !(e as KeyedEvent).shiftKey,
  alt: e => !(e as KeyedEvent).altKey,
  meta: e => !(e as KeyedEvent).metaKey,
  left: e => 'button' in e && (e as MouseEvent).button !== 0,
  middle: e => 'button' in e && (e as MouseEvent).button !== 1,
  right: e => 'button' in e && (e as MouseEvent).button !== 2,
  exact: (e, modifiers) =>
    systemModifiers.some(m => (e as any)[`${m}Key`] && !modifiers.includes(m))
}

v-on作用于組件綁定自定義事件

實現(xiàn)案例
  • 父組件中 有個子組件son, 使用v-on綁定了子組件的自定義事件,還有一個p顯示當前的時間戳。
<Son v-on:children-clicked="childClickedHandler" />
<p>{{ date }}</p>

setup() {

  let childClickedHandler = (data: Date) => {
    date.value = data.getTime();
  }

  let date = ref(new Date().getTime());

  return {
    date,
    childClickedHandler
  };
},
  • 子組件中有一個div, 每次點擊會觸發(fā)自定義事件childrenClicked, 并且傳遞了一個參數(shù)值為當前時間。
<div v-on:click="clickevent">點擊我吧</div>

emits: ["childrenClicked"],
setup(props, {emit}) {

  let clickevent = () => {
    emit('childrenClicked', new Date());
  }
  return {clickevent};
},            

這樣點擊子組件后就會觸發(fā)父組件的childClickedHandler方法,從而更新當前時間戳的顯示。

接下來我們就來看看這底層的邏輯是如何實現(xiàn)的?

實現(xiàn)邏輯
  • 先看下兩個組件的渲染函數(shù)的重點部分

父組件:

_createVNode(_component_Son, { onChildrenClicked: childClickedHandler }, null, 8 /* PROPS */, ["onChildrenClicked"])

父組件給子組件綁定自定義事件是傳遞了一個事件pro,這個pro的名稱用駝峰命名, 例如本例中的onChildrenClicked。

子組件:

const _hoisted_1 = ["onClick"]

_createElementBlock("div", {
    onClick: $event => ($emit('childrenClicked', new Date()))
}, "點擊我吧", 8 /* PROPS */, _hoisted_1)

子組件div點擊的綁定前面說過,點擊的時候執(zhí)行$emit('childrenClicked', new Date(), 這個沒有什么特別的。

現(xiàn)在的問題就是為什么子組件$emit('childrenClicked', new Date()如何找到父組件的onChildrenClicked方法并執(zhí)行?

  • $emit來自于createSetupContext函數(shù)調(diào)用時候傳入的參數(shù)setupContext
export function createSetupContext(
  instance: ComponentInternalInstance
): SetupContext {
    return {
      get attrs() {
        return attrs || (attrs = createAttrsProxy(instance))
      },
      slots: instance.slots,
      emit: instance.emit,
      expose
    }
  }
}

$emit就是組件實例的emit方法。

  • 實例的emit方法用于尋找對應(yīng)的自定義事件的函數(shù)
export function emit(
  instance: ComponentInternalInstance,
  event: string,
  ...rawArgs: any[]
) {
  const props = instance.vnode.props || EMPTY_OBJ

  // 傳入的傳參
  let args = rawArgs
  
  // TODO: 處理v-mode的方法
  const isModelListener = event.startsWith('update:')

  // 處理函數(shù)名,on+首字母大寫的函數(shù)名 或者 on+駝峰命名的函數(shù)名 
  let handlerName
  let handler =
    props[(handlerName = toHandlerKey(event))] ||
    props[(handlerName = toHandlerKey(camelize(event)))]
  if (!handler && isModelListener) {
    handler = props[(handlerName = toHandlerKey(hyphenate(event)))]
  }

  if (handler) {
    // 調(diào)用函數(shù),參數(shù)是外部傳入的參數(shù)
    callWithAsyncErrorHandling(
      handler,
      instance,
      ErrorCodes.COMPONENT_EVENT_HANDLER,
      args
    )
  }
  
}
  1. 如果函數(shù)名以update:開頭,說明是一個v-model的修改數(shù)據(jù)函數(shù),這部分邏輯會在v-model專門的文章中介紹;
  2. 然后在實例對象的props中找on+首字母大寫的函數(shù)名的函數(shù),如果沒找到,則找on+首字母大寫且駝峰命名的函數(shù)名的函數(shù);
  3. 如果找到了對應(yīng)的函數(shù),則調(diào)用函數(shù),調(diào)用函數(shù)的參數(shù)為傳入的參數(shù)。

總結(jié)

  1. v-on作用于普通元素底層是利用 addEventListenerremoveEventListener,修飾符要么利用W3C標準,要么利用函數(shù)調(diào)用來實現(xiàn);
  2. v-on作用于組件是 子組件利用 emitpro 中搜尋到對應(yīng)的函數(shù)(由父組件傳入),然后執(zhí)行對應(yīng)的函數(shù)。
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容