answershuto / learnVue

:octocat:Vue.js 源码解析
https://github.com/answershuto/learnVue
12.66k stars 2.58k forks source link

$emit的时候,为什么要将类数组换成数组?哪里有类数组?不都是vue自己建的吗 #70

Open zhishaofei3 opened 4 years ago

zhishaofei3 commented 4 years ago
Vue.prototype.$emit = function (event: string): Component {
    const vm: Component = this
    if (process.env.NODE_ENV !== 'production') {
      const 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}".`
        )
      }
    }
    let cbs = vm._events[event]
    if (cbs) {
      /*将类数组的对象转换成数组*/
      cbs = cbs.length > 1 ? toArray(cbs) : cbs
      const args = toArray(arguments, 1)
      /*遍历执行*/
      for (let i = 0, l = cbs.length; i < l; i++) {
        cbs[i].apply(vm, args)
      }
    }
    return vm
  }

$emit的时候,为什么要将类数组换成数组?哪里有类数组?什么情况下会是类数组?我看就是$on的时候Vue自己建的数组啊