index.js 2.0 KB
Newer Older
fxy060608's avatar
fxy060608 已提交
1 2 3 4
import {
  cached,
  camelize
} from 'uni-shared'
Q
qiang 已提交
5
import { markMPComponent } from './wrapper/util'
fxy060608's avatar
fxy060608 已提交
6

fxy060608's avatar
fxy060608 已提交
7 8
const MPPage = Page
const MPComponent = Component
fxy060608's avatar
fxy060608 已提交
9 10 11 12 13 14 15 16

const customizeRE = /:/g

const customize = cached((str) => {
  return camelize(str.replace(customizeRE, '-'))
})

function initTriggerEvent (mpInstance) {
fxy060608's avatar
fxy060608 已提交
17
  const oldTriggerEvent = mpInstance.triggerEvent
Q
qiang 已提交
18
  const newTriggerEvent = function (event, ...args) {
19 20 21 22 23 24 25 26 27 28 29
    // 事件名统一转驼峰格式,仅处理:当前组件为 vue 组件、当前组件为 vue 组件子组件
    if (this.$vm || (this.dataset && this.dataset.comType)) {
      event = customize(event)
    } else if (__PLATFORM__ === 'mp-weixin' || __PLATFORM__ === 'mp-qq') {
      // 针对微信/QQ小程序单独补充驼峰格式事件,以兼容历史项目
      const newEvent = customize(event)
      if (newEvent !== event) {
        oldTriggerEvent.apply(this, [newEvent, ...args])
      }
    }
    return oldTriggerEvent.apply(this, [event, ...args])
fxy060608's avatar
fxy060608 已提交
30
  }
Q
qiang 已提交
31 32 33 34 35 36
  try {
    // 京东小程序 triggerEvent 为只读
    mpInstance.triggerEvent = newTriggerEvent
  } catch (error) {
    mpInstance._triggerEvent = newTriggerEvent
  }
fxy060608's avatar
fxy060608 已提交
37 38
}

39 40 41
function initHook (name, options, isComponent) {
  if (__PLATFORM__ === 'mp-toutiao') {
    // fix by Lxh 字节自定义组件Component构造器文档上写有created,但是实测只触发了lifetimes上的created
42
    isComponent && options.lifetimes && options.lifetimes[name] && (options = options.lifetimes)
43
  }
fxy060608's avatar
fxy060608 已提交
44
  const oldHook = options[name]
Q
qiang 已提交
45 46 47 48
  options[name] = function (...args) {
    markMPComponent(this)
    initTriggerEvent(this)
    if (oldHook) {
fxy060608's avatar
fxy060608 已提交
49 50 51 52
      return oldHook.apply(this, args)
    }
  }
}
fxy060608's avatar
fxy060608 已提交
53 54 55 56 57 58 59
if (!MPPage.__$wrappered) {
  MPPage.__$wrappered = true
  Page = function (options = {}) {
    initHook('onLoad', options)
    return MPPage(options)
  }
  Page.after = MPPage.after
fxy060608's avatar
fxy060608 已提交
60

fxy060608's avatar
fxy060608 已提交
61
  Component = function (options = {}) {
62
    initHook('created', options, true)
fxy060608's avatar
fxy060608 已提交
63 64
    return MPComponent(options)
  }
65
}