component-parser.js 2.3 KB
Newer Older
fxy060608's avatar
fxy060608 已提交
1
import {
Q
qiang 已提交
2 3
  hasOwn,
  noop
4 5
} from 'uni-shared'

fxy060608's avatar
fxy060608 已提交
6 7 8 9
import {
  stringifyQuery
} from 'uni-shared/query'

10 11
import {
  isPage,
fxy060608's avatar
fxy060608 已提交
12 13 14 15 16
  initRelation
} from './util'

import parseBaseComponent from '../../../mp-weixin/runtime/wrapper/component-base-parser'

17 18
const newLifecycle = swan.canIUse('lifecycle-2-0')

fxy060608's avatar
fxy060608 已提交
19
export default function parseComponent (vueOptions) {
fxy060608's avatar
fxy060608 已提交
20 21 22
  const componentOptions = parseBaseComponent(vueOptions, {
    isPage,
    initRelation
雪洛's avatar
雪洛 已提交
23 24 25 26
  })

  // 关于百度小程序生命周期的说明(组件作为页面时):
  // lifetimes:attached --> methods:onShow --> methods:onLoad --> methods:onReady
27
  // 这里在强制将onShow挪到onLoad之后触发,另外一处修改在page-parser.js
Q
qiang 已提交
28 29 30 31 32 33 34 35
  let oldAttached = componentOptions.lifetimes.attached
  // 百度小程序基础库 3.260 以上支持页面 onInit 生命周期,提前创建 vm 实例
  componentOptions.lifetimes.onInit = function onInit (query) {
    oldAttached.call(this)
    oldAttached = noop
    this.pageinstance.$vm = this.$vm
    this.$vm.__call_hook('onInit', query)
  }
fxy060608's avatar
fxy060608 已提交
36
  componentOptions.lifetimes.attached = function attached () {
fxy060608's avatar
fxy060608 已提交
37
    oldAttached.call(this)
Q
qiang 已提交
38
    if (isPage.call(this)) { // 百度 onLoad 在 attached 之前触发(基础库小于 3.70)
fxy060608's avatar
fxy060608 已提交
39 40
      // 百度 当组件作为页面时 pageinstancce 不是原来组件的 instance
      this.pageinstance.$vm = this.$vm
41
      if (hasOwn(this.pageinstance, '_$args')) {
fxy060608's avatar
fxy060608 已提交
42 43 44 45 46 47 48 49
        const query = this.pageinstance._$args
        const copyQuery = Object.assign({}, query)
        delete copyQuery.__id__
        this.pageinstance.$page = this.$page = {
          fullPath: '/' + this.pageinstance.route + stringifyQuery(copyQuery)
        }
        this.$vm.$mp.query = query
        this.$vm.__call_hook('onLoad', query)
50
        this.$vm.__call_hook('onShow')
51
        delete this.pageinstance._$args
fxy060608's avatar
fxy060608 已提交
52
      }
雪洛's avatar
雪洛 已提交
53 54
    } else {
      // 百度小程序组件不触发methods内的onReady
55 56 57
      if (this.$vm) {
        this.$vm._isMounted = true
        this.$vm.__call_hook('mounted')
58
      }
fxy060608's avatar
fxy060608 已提交
59 60 61
    }
  }

雪洛's avatar
雪洛 已提交
62 63 64 65 66
  if (newLifecycle) {
    componentOptions.methods.onReady = componentOptions.lifetimes.ready
    delete componentOptions.lifetimes.ready
  }

fxy060608's avatar
fxy060608 已提交
67
  componentOptions.messages = {
fxy060608's avatar
fxy060608 已提交
68
    __l: componentOptions.methods.__l
fxy060608's avatar
fxy060608 已提交
69
  }
fxy060608's avatar
fxy060608 已提交
70
  delete componentOptions.methods.__l
fxy060608's avatar
fxy060608 已提交
71 72

  return componentOptions
Q
qiang 已提交
73
}