mp.js 20.7 KB
Newer Older
fxy060608's avatar
fxy060608 已提交
1 2
import Vue from 'vue';

fxy060608's avatar
fxy060608 已提交
3 4 5 6
function parseData (data, vueComponentOptions) {
  if (!data) {
    return
  }
fxy060608's avatar
fxy060608 已提交
7 8 9 10
  vueComponentOptions.mpOptions.data = data;
}

function parseComponents (vueComponentOptions) {
fxy060608's avatar
fxy060608 已提交
11
  vueComponentOptions.components = global.__wxVueOptions.components;
fxy060608's avatar
fxy060608 已提交
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
}

const _toString = Object.prototype.toString;
const hasOwnProperty = Object.prototype.hasOwnProperty;

function isFn (fn) {
  return typeof fn === 'function'
}

function isPlainObject (obj) {
  return _toString.call(obj) === '[object Object]'
}

function hasOwn (obj, key) {
  return hasOwnProperty.call(obj, key)
fxy060608's avatar
fxy060608 已提交
27 28
}

29
function noop () {}
fxy060608's avatar
fxy060608 已提交
30 31 32 33 34 35 36 37 38

/**
 * Create a cached version of a pure function.
 */
function cached (fn) {
  const cache = Object.create(null);
  return function cachedFn (str) {
    const hit = cache[str];
    return hit || (cache[str] = fn(str))
fxy060608's avatar
fxy060608 已提交
39 40 41
  }
}

fxy060608's avatar
fxy060608 已提交
42 43 44 45 46 47 48 49 50 51
/**
 * Camelize a hyphen-delimited string.
 */
const camelizeRE = /-(\w)/g;
const camelize = cached((str) => {
  return str.replace(camelizeRE, (_, c) => c ? c.toUpperCase() : '')
});

const SOURCE_KEY = '__data__';

fxy060608's avatar
fxy060608 已提交
52
const COMPONENT_LIFECYCLE = {
fxy060608's avatar
fxy060608 已提交
53 54 55 56 57
  created: 'onServiceCreated',
  attached: 'onServiceAttached',
  ready: 'mounted',
  moved: 'moved',
  detached: 'destroyed'
fxy060608's avatar
fxy060608 已提交
58 59 60 61 62 63 64 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 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118
};

const COMPONENT_LIFECYCLE_KEYS = Object.keys(COMPONENT_LIFECYCLE);

const PAGE_LIFETIMES = {
  show: 'onPageShow',
  hide: 'onPageHide',
  resize: 'onPageResize'
};

const PAGE_LIFETIMES_KEYS = Object.keys(PAGE_LIFETIMES);

const PAGE_LIFECYCLE = [
  'onLoad',
  'onShow',
  'onReady',
  'onHide',
  'onUnload',
  'onPullDownRefresh',
  'onReachBottom',
  'onShareAppMessage',
  'onPageScroll',
  'onResize',
  'onTabItemTap'
];

function parsePageMethods (mpComponentOptions, vueComponentOptions) {
  const methods = Object.create(null);
  Object.keys(mpComponentOptions).forEach(key => {
    const value = mpComponentOptions[key];
    if (isFn(value) && PAGE_LIFECYCLE.indexOf(key) === -1) {
      methods[key] = value;
    }
  });
  vueComponentOptions.methods = methods;
}

function parsePageLifecycle (mpComponentOptions, vueComponentOptions) {
  Object.keys(mpComponentOptions).forEach(key => {
    if (PAGE_LIFECYCLE.indexOf(key) !== -1) {
      vueComponentOptions[key] = mpComponentOptions[key];
    }
  });
}

function parsePage (mpComponentOptions) {
  const vueComponentOptions = {
    mixins: [],
    mpOptions: {}
  };

  parseComponents(vueComponentOptions);

  parseData(mpComponentOptions.data, vueComponentOptions);

  parsePageMethods(mpComponentOptions, vueComponentOptions);
  parsePageLifecycle(mpComponentOptions, vueComponentOptions);

  return vueComponentOptions
}

fxy060608's avatar
fxy060608 已提交
119 120 121 122
function parseProperties (properties, vueComponentOptions) {
  if (!properties) {
    return
  }
fxy060608's avatar
fxy060608 已提交
123
  vueComponentOptions.mpOptions.properties = properties;
fxy060608's avatar
fxy060608 已提交
124 125
}

fxy060608's avatar
fxy060608 已提交
126 127 128 129 130 131 132 133 134 135 136
function parseOptions (options, vueComponentOptions) {
  if (!options) {
    return
  }
  vueComponentOptions.mpOptions.options = options;
}

function parseMethods (methods, vueComponentOptions) {
  if (!methods) {
    return
  }
fxy060608's avatar
fxy060608 已提交
137
  if (methods.$emit) {
fxy060608's avatar
fxy060608 已提交
138
    console.warn('Method "$emit" conflicts with an existing Vue instance method');
fxy060608's avatar
fxy060608 已提交
139 140
    delete methods.$emit;
  }
fxy060608's avatar
fxy060608 已提交
141 142 143 144
  vueComponentOptions.methods = methods;
}

function parseLifecycle (mpComponentOptions, vueComponentOptions) {
fxy060608's avatar
fxy060608 已提交
145
  COMPONENT_LIFECYCLE_KEYS.forEach(name => {
fxy060608's avatar
fxy060608 已提交
146
    if (hasOwn(mpComponentOptions, name)) {
fxy060608's avatar
fxy060608 已提交
147 148
      (vueComponentOptions[COMPONENT_LIFECYCLE[name]] || (vueComponentOptions[COMPONENT_LIFECYCLE[name]] = []))
        .push(mpComponentOptions[name]);
fxy060608's avatar
fxy060608 已提交
149
    }
fxy060608's avatar
fxy060608 已提交
150
  });
fxy060608's avatar
fxy060608 已提交
151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 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
}

const mpBehaviors = {
  'wx://form-field': {},
  'wx://component-export': {}
};

function callDefinitionFilter (mpComponentOptions) {
  const {
    behaviors,
    definitionFilter
  } = mpComponentOptions;

  const behaviorDefinitionFilters = [];

  if (Array.isArray(behaviors)) {
    behaviors.forEach(behavior => {
      behavior = typeof behavior === 'string' ? mpBehaviors[behavior] : behavior;
      if (behavior.definitionFilter) {
        behaviorDefinitionFilters.push(behavior.definitionFilter);
        behavior.definitionFilter.call(null, mpComponentOptions, []);
      }
    });
  }

  if (isFn(definitionFilter)) {
    return function (defFields) {
      definitionFilter(defFields, behaviorDefinitionFilters);
    }
  }
}

function parseDefinitionFilter (mpComponentOptions, vueComponentOptions) {
  callDefinitionFilter(mpComponentOptions);
}

function parseBehavior (behavior) {
  const {
    data,
    methods,
fxy060608's avatar
fxy060608 已提交
191
    behaviors,
fxy060608's avatar
fxy060608 已提交
192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212
    properties
  } = behavior;

  const vueComponentOptions = {
    watch: {},
    mpOptions: {
      mpObservers: []
    }
  };

  parseData(data, vueComponentOptions);
  parseMethods(methods, vueComponentOptions);
  parseBehaviors(behaviors, vueComponentOptions);
  parseProperties(properties, vueComponentOptions);

  parseLifecycle(behavior, vueComponentOptions);
  parseDefinitionFilter(behavior);

  return vueComponentOptions
}

fxy060608's avatar
fxy060608 已提交
213 214 215 216 217 218 219 220 221 222
const BEHAVIORS = {
  'wx://form-field': {
    beforeCreate () {
      const mpOptions = this.$options.mpOptions;
      if (!mpOptions.properties) {
        mpOptions.properties = Object.create(null);
      }

      const props = mpOptions.properties;
      // TODO form submit,reset
fxy060608's avatar
fxy060608 已提交
223
      if (!hasOwn(props, 'name')) {
fxy060608's avatar
fxy060608 已提交
224 225 226 227
        props.name = {
          type: String
        };
      }
fxy060608's avatar
fxy060608 已提交
228
      if (!hasOwn(props, 'value')) {
fxy060608's avatar
fxy060608 已提交
229
        props.value = {
fxy060608's avatar
fxy060608 已提交
230
          type: String // 默认类型调整为 String,否则默认值为 null,导致一些自定义 input 显示不正确
fxy060608's avatar
fxy060608 已提交
231 232 233 234 235 236
        };
      }
    }
  }
};

fxy060608's avatar
fxy060608 已提交
237 238 239 240 241 242
function parseBehaviors (behaviors, vueComponentOptions) {
  if (!behaviors) {
    return
  }
  behaviors.forEach(behavior => {
    if (typeof behavior === 'string') {
fxy060608's avatar
fxy060608 已提交
243
      BEHAVIORS[behavior] && vueComponentOptions.mixins.push(BEHAVIORS[behavior]);
fxy060608's avatar
fxy060608 已提交
244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274
    } else {
      vueComponentOptions.mixins.push(parseBehavior(behavior));
    }
  });
}

function parseSinglePath (path) {
  return path.split('.')
}

function parseMultiPaths (paths) {
  return paths.split(',').map(path => parseSinglePath(path))
}

function parseObservers (observers, vueComponentOptions) {
  if (!observers) {
    return
  }

  const {
    mpObservers
  } = vueComponentOptions.mpOptions;

  Object.keys(observers).forEach(path => {
    mpObservers.push({
      paths: parseMultiPaths(path),
      observer: observers[path]
    });
  });
}

fxy060608's avatar
fxy060608 已提交
275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294
function relative (from, to) {
  if (to.indexOf('/') === 0) {
    from = '';
  }
  const fromArr = from.split('/');
  const toArr = to.split('/');
  fromArr.pop();
  while (toArr.length) {
    const part = toArr.shift();
    if (part !== '' && part !== '.') {
      if (part !== '..') {
        fromArr.push(part);
      } else {
        fromArr.pop();
      }
    }
  }
  return fromArr.join('/')
}

fxy060608's avatar
fxy060608 已提交
295 296 297 298
function parseRelations (relations, vueComponentOptions) {
  if (!relations) {
    return
  }
fxy060608's avatar
fxy060608 已提交
299 300 301
  Object.keys(relations).forEach(name => {
    const relation = relations[name];
    relation.name = name;
fxy060608's avatar
fxy060608 已提交
302
    relation.target = relation.target ? String(relation.target) : relative(global.__wxRoute, name);
fxy060608's avatar
fxy060608 已提交
303
  });
fxy060608's avatar
fxy060608 已提交
304 305 306 307 308 309 310
  vueComponentOptions.mpOptions.relations = relations;
}

function parseExternalClasses (externalClasses, vueComponentOptions) {
  if (!externalClasses) {
    return
  }
fxy060608's avatar
fxy060608 已提交
311 312 313
  if (!Array.isArray(externalClasses)) {
    externalClasses = [externalClasses];
  }
fxy060608's avatar
fxy060608 已提交
314
  vueComponentOptions.mpOptions.externalClasses = externalClasses;
fxy060608's avatar
fxy060608 已提交
315 316 317 318 319 320 321 322 323
  if (!vueComponentOptions.mpOptions.properties) {
    vueComponentOptions.mpOptions.properties = Object.create(null);
  }
  externalClasses.forEach(externalClass => {
    vueComponentOptions.mpOptions.properties[camelize(externalClass)] = {
      type: String,
      value: ''
    };
  });
fxy060608's avatar
fxy060608 已提交
324 325 326 327 328 329 330 331 332
}

function parseLifetimes (lifetimes, vueComponentOptions) {
  if (!lifetimes) {
    return
  }
  parseLifecycle(lifetimes, vueComponentOptions);
}

fxy060608's avatar
fxy060608 已提交
333 334 335 336 337 338 339 340 341 342
function parsePageLifetimes (pageLifetimes, vueComponentOptions) {
  if (!pageLifetimes) {
    return
  }
  PAGE_LIFETIMES_KEYS.forEach(key => {
    const lifetimeFn = pageLifetimes[key];
    isFn(lifetimeFn) && (vueComponentOptions[PAGE_LIFETIMES[key]] = lifetimeFn);
  });
}

fxy060608's avatar
fxy060608 已提交
343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358
function parseComponent (mpComponentOptions) {
  const {
    data,
    options,
    methods,
    behaviors,
    lifetimes,
    observers,
    relations,
    properties,
    pageLifetimes,
    externalClasses
  } = mpComponentOptions;

  const vueComponentOptions = {
    mixins: [],
fxy060608's avatar
fxy060608 已提交
359
    props: {},
fxy060608's avatar
fxy060608 已提交
360 361 362 363 364 365
    watch: {},
    mpOptions: {
      mpObservers: []
    }
  };

fxy060608's avatar
fxy060608 已提交
366 367
  parseComponents(vueComponentOptions);

fxy060608's avatar
fxy060608 已提交
368 369 370 371 372 373 374 375
  parseData(data, vueComponentOptions);
  parseOptions(options, vueComponentOptions);
  parseMethods(methods, vueComponentOptions);
  parseBehaviors(behaviors, vueComponentOptions);
  parseLifetimes(lifetimes, vueComponentOptions);
  parseObservers(observers, vueComponentOptions);
  parseRelations(relations, vueComponentOptions);
  parseProperties(properties, vueComponentOptions);
fxy060608's avatar
fxy060608 已提交
376
  parsePageLifetimes(pageLifetimes, vueComponentOptions);
fxy060608's avatar
fxy060608 已提交
377 378 379 380 381 382 383 384
  parseExternalClasses(externalClasses, vueComponentOptions);

  parseLifecycle(mpComponentOptions, vueComponentOptions);
  parseDefinitionFilter(mpComponentOptions);

  return vueComponentOptions
}

fxy060608's avatar
fxy060608 已提交
385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480
function initRelationHandlers (type, handler, target, ctx) {
  if (!handler) {
    return
  }
  const name = `_$${type}Handlers`;
  (ctx[name] || (ctx[name] = [])).push(function () {
    handler.call(ctx, target);
  });
}

function initLinkedHandlers (relation, target, ctx) {
  const type = 'linked';
  const name = relation.name;
  const relationNodes = ctx._$relationNodes || (ctx._$relationNodes = Object.create(null));
  (relationNodes[name] || (relationNodes[name] = [])).push(target);
  initRelationHandlers(type, relation[type], target, ctx);
}

function initUnlinkedHandlers (relation, target, ctx) {
  const type = 'unlinked';
  initRelationHandlers(type, relation[type], target, ctx);
}

function findParentRelation (parentVm, target, type) {
  const relations = parentVm &&
    parentVm.$options.mpOptions &&
    parentVm.$options.mpOptions.relations;

  if (!relations) {
    return []
  }
  const name = Object.keys(relations).find(name => {
    const relation = relations[name];
    return relation.target === target && relation.type === type
  });
  if (!name) {
    return []
  }
  return [relations[name], parentVm]
}

function initParentRelation (vm, childRelation, match) {
  const [parentRelation, parentVm] = match(vm, vm.$options.mpOptions.path);
  if (!parentRelation) {
    return
  }

  initLinkedHandlers(parentRelation, vm, parentVm);
  initLinkedHandlers(childRelation, parentVm, vm);

  initUnlinkedHandlers(parentRelation, vm, parentVm);
  initUnlinkedHandlers(childRelation, parentVm, vm);
}

function initRelation (relation, vm) {
  const type = relation.type;
  if (type === 'parent') {
    initParentRelation(vm, relation, function matchParent (vm, target) {
      return findParentRelation(vm.$parent, target, 'child')
    });
  } else if (type === 'ancestor') {
    initParentRelation(vm, relation, function matchAncestor (vm, target) {
      let $parent = vm.$parent;
      while ($parent) {
        const ret = findParentRelation($parent, target, 'descendant');
        if (ret.length) {
          return ret
        }
        $parent = $parent.$parent;
      }
      return []
    });
  }
}

function initRelations (vm) {
  const {
    relations
  } = vm.$options.mpOptions || {};
  if (!relations) {
    return
  }
  Object.keys(relations).forEach(name => {
    initRelation(relations[name], vm);
  });
}

function handleRelations (vm, type) {
  // TODO 需要移除 relationNodes
  const handlers = vm[`_$${type}Handlers`];
  if (!handlers) {
    return
  }
  handlers.forEach(handler => handler());
}

fxy060608's avatar
fxy060608 已提交
481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497
const sharedPropertyDefinition = {
  enumerable: true,
  configurable: true,
  get: noop,
  set: noop
};

function proxy (target, sourceKey, key) {
  sharedPropertyDefinition.get = function proxyGetter () {
    return this[sourceKey][key]
  };
  sharedPropertyDefinition.set = function proxySetter (val) {
    this[sourceKey][key] = val;
  };
  Object.defineProperty(target, key, sharedPropertyDefinition);
}

fxy060608's avatar
fxy060608 已提交
498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525
function setDataByExprPath (exprPath, value, data) {
  const keys = exprPath.replace(/\[(\d+?)\]/g, '.$1').split('.');
  keys.reduce((obj, key, idx) => {
    if (idx === keys.length - 1) {
      obj[key] = value;
    } else {
      if (typeof obj[key] === 'undefined') {
        obj[key] = {};
      }
      return obj[key]
    }
  }, data);
  return keys.length === 1
}

function setData (data, callback) {
  if (!isPlainObject(data)) {
    return
  }
  Object.keys(data).forEach(key => {
    if (setDataByExprPath(key, data[key], this.data)) {
      !hasOwn(this, key) && proxy(this, SOURCE_KEY, key);
    }
  });
  this.$forceUpdate();
  isFn(callback) && this.$nextTick(callback);
}

fxy060608's avatar
fxy060608 已提交
526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554
/**
 * https://github.com/swan-team/swan-js/blob/61e2a63f7aa576b5daafbe77fdfa7c65b977060c/src/utils/index.js
 */

const _toString$1 = Object.prototype.toString;
/**
 * 深度assign的函数
 * @param {Object} targetObject 要被拷贝的目标对象
 * @param {Object} originObject 拷贝的源对象
 * @return {Object} merge后的对象
 */
const deepAssign = (targetObject = {}, originObject) => {
  const originType = _toString$1.call(originObject);
  if (originType === '[object Array]') {
    targetObject = originObject.slice(0);
    return targetObject
  } else if (originType === '[object Object]') {
    for (const key in originObject) {
      targetObject[key] = deepAssign(targetObject[key], originObject[key]);
    }
    return targetObject
  } else if (originType === '[object Date]') {
    return new Date(originObject.getTime())
  } else if (originType === '[object RegExp]') {
    const target = String(originObject);
    const lastIndex = target.lastIndexOf('/');
    return new RegExp(target.slice(1, lastIndex), target.slice(lastIndex + 1))
  }
  return originObject
fxy060608's avatar
fxy060608 已提交
555 556
};

fxy060608's avatar
fxy060608 已提交
557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573
/**
 * 深度拷贝逻辑,不同于lodash等库,但是与微信一致
 * @param {*} [originObj] 原对象
 * @return {Object|Array} 拷贝结果
 */
const deepClone = originObj => {
  return deepAssign(_toString$1.call(originObj) === '[object Array]' ? [] : {}, originObj)
};

const PROP_DEFAULT_VALUES = {
  [String]: '',
  [Number]: 0,
  [Boolean]: false,
  [Object]: null,
  [Array]: [],
  [null]: null
};
fxy060608's avatar
fxy060608 已提交
574

fxy060608's avatar
fxy060608 已提交
575
function getDefaultVal (propType) {
fxy060608's avatar
fxy060608 已提交
576
  return PROP_DEFAULT_VALUES[propType]
fxy060608's avatar
fxy060608 已提交
577 578 579 580 581 582 583 584 585
}

function getPropertyVal (options) {
  if (isPlainObject(options)) {
    if (hasOwn(options, 'value')) {
      return options.value
    }
    return getDefaultVal(options.type)
  }
fxy060608's avatar
fxy060608 已提交
586
  return getDefaultVal(options)
fxy060608's avatar
fxy060608 已提交
587 588 589 590 591 592 593 594 595 596 597
}

function getType (propOptions) {
  return isPlainObject(propOptions) ? propOptions.type : propOptions
}

function validateProp (key, propsOptions, propsData, vm) {
  let value = propsData[key];
  if (value !== undefined) {
    const propOptions = propsOptions[key];
    const type = getType(propOptions);
598
    value = formatVal(value, type);
fxy060608's avatar
fxy060608 已提交
599
    const observer = propOptions && propOptions.observer;
fxy060608's avatar
fxy060608 已提交
600 601 602 603 604 605
    if (observer) {
      // 初始化时,异步触发 observer,否则 observer 中无法访问 methods 或其他
      setTimeout(function () {
        observe(observer, vm, value);
      }, 4);
    }
fxy060608's avatar
fxy060608 已提交
606 607 608 609 610
    return value
  }
  return getPropertyVal(propsOptions[key])
}

611 612 613 614 615 616 617 618 619
function formatVal (val, type) {
  if (type === Boolean) {
    return !!val
  } else if (type === String) {
    return String(val)
  }
  return val
}

fxy060608's avatar
fxy060608 已提交
620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638
function observe (observer, vm, newVal, oldVal) {
  try {
    if (typeof observer === 'function') {
      observer.call(vm, newVal, oldVal);
    } else if (typeof observer === 'string' &&
      typeof vm[observer] === 'function'
    ) {
      vm[observer](newVal, oldVal);
    }
  } catch (err) {
    console.error(`execute observer ${observer} callback fail! err: ${err}`);
  }
}

function initProperties (vm, instanceData) {
  const properties = vm.$options.mpOptions.properties;
  if (!properties) {
    return
  }
fxy060608's avatar
fxy060608 已提交
639 640

  const propsData = deepClone(vm.$options.propsData) || {};
fxy060608's avatar
fxy060608 已提交
641 642 643 644 645 646 647 648 649 650 651

  for (const key in properties) {
    const observer = isPlainObject(properties[key]) ? properties[key].observer : false;
    let value = validateProp(key, properties, propsData, vm);
    Object.defineProperty(instanceData, key, {
      enumerable: true,
      configurable: true,
      get () {
        return value
      },
      set (newVal) {
fxy060608's avatar
fxy060608 已提交
652 653 654 655
        const oldVal = value;
        /* eslint-disable no-self-compare */
        if (newVal === value || (newVal !== newVal && value !== value)) {
          return
fxy060608's avatar
fxy060608 已提交
656
        }
fxy060608's avatar
fxy060608 已提交
657 658
        // TODO 临时方案,clone array
        value = Array.isArray(newVal) ? newVal.slice(0) : newVal;
fxy060608's avatar
fxy060608 已提交
659 660 661
        if (observer) {
          observe(observer, vm, newVal, oldVal);
        }
fxy060608's avatar
fxy060608 已提交
662 663
        // 触发渲染
        vm.$forceUpdate();
fxy060608's avatar
fxy060608 已提交
664 665 666 667 668 669
      }
    });
  }
}

function updateProperties (vm) {
fxy060608's avatar
fxy060608 已提交
670
  const properties = vm.$options.mpOptions && vm.$options.mpOptions.properties;
fxy060608's avatar
fxy060608 已提交
671 672 673 674
  const propsData = vm.$options.propsData;
  if (propsData && properties) {
    Object.keys(properties).forEach(key => {
      if (hasOwn(propsData, key)) {
675
        vm[key] = formatVal(propsData[key], getType(properties[key]));
fxy060608's avatar
fxy060608 已提交
676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699
      }
    });
  }
}

function initState (vm) {
  const instanceData = JSON.parse(JSON.stringify(vm.$options.mpOptions.data || {}));

  vm[SOURCE_KEY] = instanceData;

  const propertyDefinition = {
    get () {
      return vm[SOURCE_KEY]
    },
    set (value) {
      vm[SOURCE_KEY] = value;
    }
  };

  Object.defineProperties(vm, {
    data: propertyDefinition,
    properties: propertyDefinition
  });

fxy060608's avatar
fxy060608 已提交
700
  vm.setData = setData;
fxy060608's avatar
fxy060608 已提交
701 702 703 704 705 706 707 708 709 710 711 712 713

  initProperties(vm, instanceData);

  Object.keys(instanceData).forEach(key => {
    proxy(vm, SOURCE_KEY, key);
  });
}

function initMethods (vm) {
  const oldEmit = vm.$emit;
  vm.triggerEvent = (eventName, detail, options) => {
    const target = {
      dataset: vm.$el.dataset
fxy060608's avatar
fxy060608 已提交
714
    };
fxy060608's avatar
fxy060608 已提交
715 716

    const event = {
fxy060608's avatar
fxy060608 已提交
717 718
      target,
      currentTarget: target,
fxy060608's avatar
fxy060608 已提交
719 720 721 722 723 724
      detail,
      preventDefault: noop,
      stopPropagation: noop
    };

    oldEmit.call(vm, eventName, event);
fxy060608's avatar
fxy060608 已提交
725 726 727 728 729 730
  };
  // 主要是Vant 自己封装了 $emit,放到 methods 中会触发 Vue 的警告,索性,框架直接重写该方法
  vm.$emit = (...args) => {
    vm.triggerEvent(...args);
  };
  vm.getRelationNodes = (relationKey) => {
fxy060608's avatar
fxy060608 已提交
731
    // 需要过滤已被销毁的vm
fxy060608's avatar
fxy060608 已提交
732
    /* eslint-disable  no-mixed-operators */
fxy060608's avatar
fxy060608 已提交
733
    return (vm._$relationNodes && vm._$relationNodes[relationKey] || []).filter(vm => !vm._isDestroyed)
fxy060608's avatar
fxy060608 已提交
734
  };
fxy060608's avatar
fxy060608 已提交
735 736

  vm._$updateProperties = updateProperties;
fxy060608's avatar
fxy060608 已提交
737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758
}

function handleObservers (vm) {
  const watch = vm.$options.watch;
  if (!watch) {
    return
  }
  Object.keys(watch).forEach(name => {
    const observer = watch[name];
    if (observer.mounted) {
      const val = vm[name];
      let handler = observer.handler;
      if (typeof handler === 'string') {
        handler = vm[handler];
      }
      handler && handler.call(vm, val, val);
    }
  });
}

var polyfill = {
  beforeCreate () {
fxy060608's avatar
fxy060608 已提交
759 760
    // 取消 development 时的 Proxy,避免小程序组件模板中使用尚未定义的属性告警
    this._renderProxy = this;
fxy060608's avatar
fxy060608 已提交
761 762 763

    this._$self = this;
    this._$noop = noop;
fxy060608's avatar
fxy060608 已提交
764 765
  },
  created () { // properties 中可能会访问 methods,故需要在 created 中初始化
fxy060608's avatar
fxy060608 已提交
766 767 768 769 770 771 772
    initState(this);
    initMethods(this);
    initRelations(this);
  },
  mounted () {
    handleObservers(this);
  },
fxy060608's avatar
fxy060608 已提交
773
  destroyed () {
fxy060608's avatar
fxy060608 已提交
774
    handleRelations(this, 'unlinked');
fxy060608's avatar
fxy060608 已提交
775 776 777
  }
};

fxy060608's avatar
fxy060608 已提交
778 779 780
global.__wxRoute = '';
global.__wxComponents = Object.create(null);
global.__wxVueOptions = Object.create(null);
fxy060608's avatar
fxy060608 已提交
781

fxy060608's avatar
fxy060608 已提交
782 783 784
function Page (options) {
  const pageOptions = parsePage(options);
  pageOptions.mixins.unshift(polyfill);
fxy060608's avatar
fxy060608 已提交
785 786
  pageOptions.mpOptions.path = global.__wxRoute;
  global.__wxComponents[global.__wxRoute] = pageOptions;
fxy060608's avatar
fxy060608 已提交
787 788
}

fxy060608's avatar
fxy060608 已提交
789 790
function initRelationsHandler (vueComponentOptions) {
  // linked 需要在当前组件 attached 之后再执行
fxy060608's avatar
fxy060608 已提交
791 792
  if (!vueComponentOptions.onServiceAttached) {
    vueComponentOptions.onServiceAttached = [];
fxy060608's avatar
fxy060608 已提交
793
  }
fxy060608's avatar
fxy060608 已提交
794
  vueComponentOptions.onServiceAttached.push(function onServiceAttached () {
fxy060608's avatar
fxy060608 已提交
795 796 797 798
    handleRelations(this, 'linked');
  });
}

fxy060608's avatar
fxy060608 已提交
799 800 801
function Component (options) {
  const componentOptions = parseComponent(options);
  componentOptions.mixins.unshift(polyfill);
fxy060608's avatar
fxy060608 已提交
802
  componentOptions.mpOptions.path = global.__wxRoute;
fxy060608's avatar
fxy060608 已提交
803
  initRelationsHandler(componentOptions);
fxy060608's avatar
fxy060608 已提交
804
  global.__wxComponents[global.__wxRoute] = componentOptions;
fxy060608's avatar
fxy060608 已提交
805 806 807 808
}

function Behavior (options) {
  return options
fxy060608's avatar
fxy060608 已提交
809 810
}

811 812 813
const nextTick = Vue.nextTick;

var index = uni.__$wx__;
fxy060608's avatar
fxy060608 已提交
814

815
export default index;
fxy060608's avatar
fxy060608 已提交
816
export { Behavior, Component, Page, nextTick };