create-app.js 1.2 KB
Newer Older
1 2 3
import Vue from 'vue'

import {
fxy060608's avatar
fxy060608 已提交
4 5
  initRefs,
  initHooks,
6
  initMocks
7 8 9 10 11 12 13 14 15 16 17
} from './util'

const hooks = [
  'onShow',
  'onHide',
  'onError',
  'onPageNotFound'
]

export function createApp (vueOptions) {
  vueOptions = vueOptions.default || vueOptions
fxy060608's avatar
fxy060608 已提交
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
  // 外部初始化时 Vue 还未初始化,放到 createApp 内部初始化 mixin
  Vue.mixin({
    beforeCreate () {
      if (!this.$options.mpType) {
        return
      }
      this.mpType = this.$options.mpType
      this.$mp = {
        data: {},
        [this.mpType]: this.$options.mpInstance
      }
      delete this.$options.mpType
      delete this.$options.mpInstance

      if (this.mpType !== 'app') {
        initRefs(this)
        initMocks(this)
      }
    }
  })
38 39 40

  const appOptions = {
    onLaunch (args) {
fxy060608's avatar
fxy060608 已提交
41 42 43 44 45
      this.$vm = new Vue(Object.assign(vueOptions, {
        mpType: 'app',
        mpInstance: this
      }))

46
      this.$vm.$mount()
fxy060608's avatar
fxy060608 已提交
47
      setTimeout(() => this.$vm.__call_hook('onLaunch', args))
48 49 50
    }
  }

fxy060608's avatar
fxy060608 已提交
51
  initHooks(appOptions, hooks, true) // 延迟执行,因为 App 的注册在 main.js 之前,可能导致生命周期内 Vue 原型上开发者注册的属性无法访问
52 53 54 55 56

  App(appOptions)

  return vueOptions
}