create-app.js 2.1 KB
Newer Older
fxy060608's avatar
fxy060608 已提交
1 2
import 'uni-platform/runtime/index'

3
import Vue from 'vue'
fxy060608's avatar
fxy060608 已提交
4 5 6 7

import {
  mocks
} from 'uni-platform/runtime/wrapper/index'
8 9

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

const hooks = [
  'onHide',
  'onError',
fxy060608's avatar
fxy060608 已提交
18 19
  'onPageNotFound',
  'onUniNViewMessage'
20 21
]

fxy060608's avatar
fxy060608 已提交
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
function initVm (vm) {
  if (this.$vm) { // 百度竟然 onShow 在 onLaunch 之前?
    return
  }
  if (__PLATFORM__ === 'mp-weixin') {
    if (!wx.canIUse('nextTick')) { // 事实 上2.2.3 即可,简单使用 2.3.0 的 nextTick 判断
      console.error('当前微信基础库版本过低,请将 微信开发者工具-详情-项目设置-调试基础库版本 更换为`2.3.0`以上')
    }
  }

  this.$vm = vm

  this.$vm.$mp = {
    app: this
  }
}

39
export function createApp (vm) {
fxy060608's avatar
fxy060608 已提交
40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
  // 外部初始化时 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') {
fxy060608's avatar
fxy060608 已提交
55 56 57
        if (__PLATFORM__ !== 'mp-toutiao') { // 头条的 selectComponent 竟然是异步的
          initRefs(this)
        }
fxy060608's avatar
fxy060608 已提交
58
        initMocks(this, mocks)
fxy060608's avatar
fxy060608 已提交
59
      }
60 61 62 63
    },
    created () { // 处理 injections
      this.__init_injections(this)
      this.__init_provide(this)
fxy060608's avatar
fxy060608 已提交
64 65
    }
  })
66 67

  const appOptions = {
fxy060608's avatar
fxy060608 已提交
68
    onLaunch (args) {
fxy060608's avatar
fxy060608 已提交
69
      initVm.call(this, vm)
fxy060608's avatar
fxy060608 已提交
70

71 72 73 74
      this.$vm._isMounted = true
      this.$vm.__call_hook('mounted')

      this.$vm.__call_hook('onLaunch', args)
fxy060608's avatar
fxy060608 已提交
75 76 77 78 79
    },
    onShow (args) {
      initVm.call(this, vm)

      this.$vm.__call_hook('onShow', args)
80 81 82
    }
  }

fxy060608's avatar
fxy060608 已提交
83 84 85
  // 兼容旧版本 globalData
  appOptions.globalData = vm.$options.globalData || {}

86
  initHooks(appOptions, hooks) // 延迟执行,因为 App 的注册在 main.js 之前,可能导致生命周期内 Vue 原型上开发者注册的属性无法访问
87 88 89

  App(appOptions)

90
  return vm
91
}