util.js 10.2 KB
Newer Older
1 2 3
import {
  isFn,
  noop,
4
  hasOwn,
5 6 7
  isPlainObject
} from 'uni-shared'

fxy060608's avatar
fxy060608 已提交
8
const MOCKS = ['__route__', '__wxExparserNodeId__', '__wxWebviewId__', '__webviewId__']
9 10 11 12 13 14 15 16 17 18

export function initMocks (vm) {
  const mpInstance = vm.$mp[vm.mpType]
  MOCKS.forEach(mock => {
    if (hasOwn(mpInstance, mock)) {
      vm[mock] = mpInstance[mock]
    }
  })
}

19
export function initHooks (mpOptions, hooks) {
20 21
  hooks.forEach(hook => {
    mpOptions[hook] = function (args) {
22
      return this.$vm.__call_hook(hook, args)
23 24 25 26
    }
  })
}

fxy060608's avatar
fxy060608 已提交
27
export function getData (vueOptions, context) {
fxy060608's avatar
fxy060608 已提交
28 29
  let data = vueOptions.data || {}
  const methods = vueOptions.methods || {}
30 31 32

  if (typeof data === 'function') {
    try {
fxy060608's avatar
fxy060608 已提交
33
      data = data.call(context) // 支持 Vue.prototype 上挂的数据
34
    } catch (e) {
35 36 37
      if (process.env.VUE_APP_DEBUG) {
        console.warn('根据 Vue 的 data 函数初始化小程序 data 失败,请尽量确保 data 函数中不访问 vm 对象,否则可能影响首次数据渲染速度。', data)
      }
38
    }
39 40 41 42 43
  } else {
    try {
      // 对 data 格式化
      data = JSON.parse(JSON.stringify(data))
    } catch (e) {}
44
  }
fxy060608's avatar
fxy060608 已提交
45

46
  Object.keys(methods).forEach(methodName => {
fxy060608's avatar
fxy060608 已提交
47
    if (context.__lifecycle_hooks__.indexOf(methodName) === -1 && !hasOwn(data, methodName)) {
48 49 50 51 52
      data[methodName] = methods[methodName]
    }
  })

  return data
53 54 55 56
}

const PROP_TYPES = [String, Number, Boolean, Object, Array, null]

fxy060608's avatar
fxy060608 已提交
57 58 59 60 61 62 63 64
function createObserver (name) {
  return function observer (newVal, oldVal) {
    if (this.$vm) {
      this.$vm[name] = newVal // 为了触发其他非 render watcher
    }
  }
}

65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
export function getBehaviors (vueExtends, vueMixins) {
  const behaviors = []
  if (isPlainObject(vueExtends) && vueExtends.props) {
    behaviors.push(
      Behavior({
        properties: getProperties(vueExtends.props, true)
      })
    )
  }
  if (Array.isArray(vueMixins)) {
    vueMixins.forEach(vueMixin => {
      if (isPlainObject(vueMixin) && vueMixin.props) {
        behaviors.push(
          Behavior({
            properties: getProperties(vueMixin.props, true)
          })
        )
      }
    })
  }
  return behaviors
}

export function getProperties (props, isBehavior = false) {
  const properties = {}
  if (!isBehavior) {
    properties.vueSlots = { // 小程序不能直接定义 $slots 的 props,所以通过 vueSlots 转换到 $slots
92 93 94 95 96 97 98 99 100 101 102 103 104
      type: null,
      value: [],
      observer: function (newVal, oldVal) {
        const $slots = Object.create(null)
        newVal.forEach(slotName => {
          $slots[slotName] = true
        })
        this.setData({
          $slots
        })
      }
    }
  }
105 106
  if (Array.isArray(props)) { // ['title']
    props.forEach(key => {
fxy060608's avatar
fxy060608 已提交
107 108 109 110
      properties[key] = {
        type: null,
        observer: createObserver(key)
      }
111 112 113 114 115 116 117 118 119 120 121
    })
  } else if (isPlainObject(props)) { // {title:{type:String,default:''},content:String}
    Object.keys(props).forEach(key => {
      const opts = props[key]
      if (isPlainObject(opts)) { // title:{type:String,default:''}
        let value = opts['default']
        if (isFn(value)) {
          value = value()
        }
        properties[key] = {
          type: PROP_TYPES.includes(opts.type) ? opts.type : null,
fxy060608's avatar
fxy060608 已提交
122 123
          value,
          observer: createObserver(key)
124 125
        }
      } else { // content:String
fxy060608's avatar
fxy060608 已提交
126 127 128 129
        properties[key] = {
          type: PROP_TYPES.includes(opts) ? opts : null,
          observer: createObserver(key)
        }
130 131 132 133 134 135 136 137 138 139 140
      }
    })
  }
  return properties
}

function wrapper (event) {
  event.stopPropagation = noop
  event.preventDefault = noop

  event.target = event.target || {}
fxy060608's avatar
fxy060608 已提交
141 142 143 144

  if (!hasOwn(event, 'detail')) {
    event.detail = {}
  }
fxy060608's avatar
fxy060608 已提交
145 146

  if (__PLATFORM__ === 'mp-baidu') { // mp-baidu,checked=>value
fxy060608's avatar
fxy060608 已提交
147 148 149 150 151
    if (
      isPlainObject(event.detail) &&
            hasOwn(event.detail, 'checked') &&
            !hasOwn(event.detail, 'value')
    ) {
fxy060608's avatar
fxy060608 已提交
152 153 154 155
      event.detail.value = event.detail.checked
    }
  }

156 157
  // TODO 又得兼容 mpvue 的 mp 对象
  event.mp = event
fxy060608's avatar
fxy060608 已提交
158 159 160 161 162

  if (isPlainObject(event.detail)) {
    event.target = Object.assign({}, event.target, event.detail)
  }

163 164 165
  return event
}

fxy060608's avatar
fxy060608 已提交
166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202
function getExtraValue (vm, dataPathsArray) {
  let context = vm
  dataPathsArray.forEach(dataPathArray => {
    const dataPath = dataPathArray[0]
    const value = dataPathArray[2]
    if (dataPath || typeof value !== 'undefined') { // ['','',index,'disable']
      const propPath = dataPathArray[1]
      const valuePath = dataPathArray[3]

      const vFor = dataPath ? vm.__get_value(dataPath, context) : context

      if (Number.isInteger(vFor)) {
        context = value
      } else if (!propPath) {
        context = vFor[value]
      } else {
        if (Array.isArray(vFor)) {
          context = vFor.find(vForItem => {
            return vm.__get_value(propPath, vForItem) === value
          })
        } else if (isPlainObject(vFor)) {
          context = Object.keys(vFor).find(vForKey => {
            return vm.__get_value(propPath, vFor[vForKey]) === value
          })
        } else {
          console.error('v-for 暂不支持循环数据:', vFor)
        }
      }

      if (valuePath) {
        context = vm.__get_value(valuePath, context)
      }
    }
  })
  return context
}

203
function processEventExtra (vm, extra, event) {
fxy060608's avatar
fxy060608 已提交
204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222
  const extraObj = {}

  if (Array.isArray(extra) && extra.length) {
    /**
         *[
         *    ['data.items', 'data.id', item.data.id],
         *    ['metas', 'id', meta.id]
         *],
         *[
         *    ['data.items', 'data.id', item.data.id],
         *    ['metas', 'id', meta.id]
         *],
         *'test'
         */
    extra.forEach((dataPath, index) => {
      if (typeof dataPath === 'string') {
        if (!dataPath) { // model,prop.sync
          extraObj['$' + index] = vm
        } else {
223 224 225 226 227 228 229
          if (dataPath === '$event') { // $event
            extraObj['$' + index] = event
          } else if (dataPath.indexOf('$event.') === 0) { // $event.target.value
            extraObj['$' + index] = vm.__get_value(dataPath.replace('$event.', ''), event)
          } else {
            extraObj['$' + index] = vm.__get_value(dataPath)
          }
fxy060608's avatar
fxy060608 已提交
230 231 232 233 234 235 236 237 238 239
        }
      } else {
        extraObj['$' + index] = getExtraValue(vm, dataPath)
      }
    })
  }

  return extraObj
}

fxy060608's avatar
fxy060608 已提交
240 241 242 243 244 245 246 247 248
function getObjByArray (arr) {
  const obj = {}
  for (let i = 1; i < arr.length; i++) {
    const element = arr[i]
    obj[element[0]] = element[1]
  }
  return obj
}

fxy060608's avatar
fxy060608 已提交
249
function processEventArgs (vm, event, args = [], extra = [], isCustom, methodName) {
fxy060608's avatar
fxy060608 已提交
250
  let isCustomMPEvent = false // wxcomponent 组件,传递原始 event 对象
251
  if (isCustom) { // 自定义事件
fxy060608's avatar
fxy060608 已提交
252
    isCustomMPEvent = event.currentTarget &&
253
            event.currentTarget.dataset &&
254
            event.currentTarget.dataset.comType === 'wx'
fxy060608's avatar
fxy060608 已提交
255 256 257 258
    if (!args.length) { // 无参数,直接传入 event 或 detail 数组
      if (isCustomMPEvent) {
        return [event]
      }
fxy060608's avatar
fxy060608 已提交
259
      return event.detail.__args__ || event.detail
260
    }
261
  }
fxy060608's avatar
fxy060608 已提交
262

263
  const extraObj = processEventExtra(vm, extra, event)
fxy060608's avatar
fxy060608 已提交
264

265 266 267
  const ret = []
  args.forEach(arg => {
    if (arg === '$event') {
fxy060608's avatar
fxy060608 已提交
268 269 270
      if (methodName === '__set_model' && !isCustom) { // input v-model value
        ret.push(event.target.value)
      } else {
fxy060608's avatar
fxy060608 已提交
271
        if (isCustom && !isCustomMPEvent) {
fxy060608's avatar
fxy060608 已提交
272
          ret.push(event.detail.__args__[0])
fxy060608's avatar
fxy060608 已提交
273 274 275
        } else { // wxcomponent 组件或内置组件
          ret.push(event)
        }
fxy060608's avatar
fxy060608 已提交
276
      }
277
    } else {
fxy060608's avatar
fxy060608 已提交
278 279 280
      if (Array.isArray(arg) && arg[0] === 'o') {
        ret.push(getObjByArray(arg))
      } else if (typeof arg === 'string' && hasOwn(extraObj, arg)) {
fxy060608's avatar
fxy060608 已提交
281 282 283 284
        ret.push(extraObj[arg])
      } else {
        ret.push(arg)
      }
285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315
    }
  })

  return ret
}

const ONCE = '~'
const CUSTOM = '^'

export function handleEvent (event) {
  event = wrapper(event)

  // [['tap',[['handle',[1,2,a]],['handle1',[1,2,a]]]]]
  const eventOpts = (event.currentTarget || event.target).dataset.eventOpts
  if (!eventOpts) {
    return console.warn(`事件信息不存在`)
  }

  // [['handle',[1,2,a]],['handle1',[1,2,a]]]
  const eventType = event.type
  eventOpts.forEach(eventOpt => {
    let type = eventOpt[0]
    const eventsArray = eventOpt[1]

    const isCustom = type.charAt(0) === CUSTOM
    type = isCustom ? type.slice(1) : type
    const isOnce = type.charAt(0) === ONCE
    type = isOnce ? type.slice(1) : type

    if (eventsArray && eventType === type) {
      eventsArray.forEach(eventArray => {
316
        const methodName = eventArray[0]
fxy060608's avatar
fxy060608 已提交
317 318 319 320 321 322 323 324 325 326
        if (methodName) {
          const handler = this.$vm[methodName]
          if (!isFn(handler)) {
            throw new Error(` _vm.${methodName} is not a function`)
          }
          if (isOnce) {
            if (handler.once) {
              return
            }
            handler.once = true
327
          }
fxy060608's avatar
fxy060608 已提交
328 329 330 331 332 333 334 335
          handler.apply(this.$vm, processEventArgs(
            this.$vm,
            event,
            eventArray[1],
            eventArray[2],
            isCustom,
            methodName
          ))
336 337 338 339 340 341 342 343 344 345
        }
      })
    }
  })
}

export function initRefs (vm) {
  const mpInstance = vm.$mp[vm.mpType]
  Object.defineProperty(vm, '$refs', {
    get () {
fxy060608's avatar
fxy060608 已提交
346
      const $refs = {}
fxy060608's avatar
fxy060608 已提交
347
      const components = mpInstance.selectAllComponents('.vue-ref')
348
      components.forEach(component => {
fxy060608's avatar
fxy060608 已提交
349
        const ref = component.dataset.ref
fxy060608's avatar
fxy060608 已提交
350
        $refs[ref] = component.$vm || component
351
      })
fxy060608's avatar
fxy060608 已提交
352
      const forComponents = mpInstance.selectAllComponents('.vue-ref-in-for')
353
      forComponents.forEach(component => {
fxy060608's avatar
fxy060608 已提交
354 355 356
        const ref = component.dataset.ref
        if (!$refs[ref]) {
          $refs[ref] = []
357
        }
fxy060608's avatar
fxy060608 已提交
358
        $refs[ref].push(component.$vm || component)
359 360 361 362
      })
      return $refs
    }
  })
fxy060608's avatar
fxy060608 已提交
363 364 365 366 367 368 369 370 371 372 373 374 375 376
}

function baiduComponentDestroy ($vm) {
  $vm.$children.forEach(childVm => {
    childVm.$mp.component.detached()
  })
  $vm.$mp.component.detached()
}

export function baiduPageDestroy ($vm) {
  $vm.$destroy()
  $vm.$children.forEach(childVm => {
    baiduComponentDestroy(childVm)
  })
377
}