parseComponentOptions.ts 2.0 KB
Newer Older
fxy060608's avatar
fxy060608 已提交
1 2 3
import { hasOwn } from '@vue/shared'

import { MPComponentInstance, MPComponentOptions } from '@dcloudio/uni-mp-core'
fxy060608's avatar
fxy060608 已提交
4
import { ON_LOAD, ON_SHOW } from '@dcloudio/uni-shared'
fxy060608's avatar
fxy060608 已提交
5 6 7 8 9 10

export { handleLink, initLifetimes } from '@dcloudio/uni-mp-weixin'

export const mocks = ['nodeId', 'componentName', '_componentId', 'uniquePrefix']

export function isPage(mpInstance: MPComponentInstance) {
fxy060608's avatar
fxy060608 已提交
11
  return !hasOwn(mpInstance, 'ownerId')
fxy060608's avatar
fxy060608 已提交
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
}

export function initRelation(mpInstance: MPComponentInstance, detail: object) {
  ;(mpInstance as any).dispatch('__l', detail)
}

const newLifecycle = /*#__PURE__*/ swan.canIUse('lifecycle-2-0')

export function parse(componentOptions: MPComponentOptions) {
  const methods = componentOptions.methods as Record<
    string,
    (...args: any[]) => any
  >
  const lifetimes = componentOptions.lifetimes as Record<string, any>

  // 关于百度小程序生命周期的说明(组件作为页面时):
  // lifetimes:attached --> methods:onShow --> methods:onLoad --> methods:onReady
  // 这里在强制将onShow挪到onLoad之后触发,另外一处修改在page-parser.js
  const oldAttached = lifetimes.attached
  lifetimes.attached = function attached(this: MPComponentInstance) {
    oldAttached.call(this)
    if (isPage(this) && this.$vm) {
      // 百度 onLoad 在 attached 之前触发
      // 百度 当组件作为页面时 pageinstance 不是原来组件的 instance
      const pageInstance = (this as any).pageinstance
      pageInstance.$vm = this.$vm
      if (hasOwn(pageInstance, '_$args')) {
fxy060608's avatar
fxy060608 已提交
39 40
        this.$vm.$callHook(ON_LOAD, pageInstance._$args)
        this.$vm.$callHook(ON_SHOW)
fxy060608's avatar
fxy060608 已提交
41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
        delete pageInstance._$args
      }
    } else {
      // 百度小程序组件不触发methods内的onReady
      if (this.$vm) {
        this.$vm.$callHook('mounted')
      }
    }
  }

  if (newLifecycle) {
    methods.onReady = lifetimes.ready
    delete lifetimes.ready
  }
  ;(componentOptions as any).messages = {
56
    __l: methods.__l,
fxy060608's avatar
fxy060608 已提交
57 58 59
  }
  delete methods.__l
}