mp.js 19.5 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 11
  vueComponentOptions.mpOptions.data = data;
}

function parseComponents (vueComponentOptions) {
  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
}

fxy060608's avatar
fxy060608 已提交
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 53 54
const COMPONENT_LIFECYCLE = {
  'created': 'onServiceCreated',
  'attached': 'onServiceAttached',
fxy060608's avatar
fxy060608 已提交
55 56 57 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
  'ready': 'mounted',
  'moved': 'moved',
  'detached': 'destroyed'
};

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 139 140
    console.warn(`Method "$emit" conflicts with an existing Vue instance method`);
    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 223 224 225 226 227 228 229 230 231 232 233 234 235 236
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
      if (!props.name) {
        props.name = {
          type: String
        };
      }
      if (!props.value) {
        props.value = {
          type: null
        };
      }
    }
  }
};

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 302 303
  Object.keys(relations).forEach(name => {
    const relation = relations[name];
    relation.name = name;
    relation.target = relation.target ? String(relation.target) : relative(global['__wxRoute'], name);
  });
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
const PROP_DEFAULT_VALUES = {
  String: '',
  Number: 0,
  Boolean: false,
  Object: null,
  Array: [],
  null: null
};

const PROP_DEFAULT_KEYS = Object.keys(PROP_DEFAULT_VALUES);
fxy060608's avatar
fxy060608 已提交
536

fxy060608's avatar
fxy060608 已提交
537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565
function getDefaultVal (type) {
  return PROP_DEFAULT_KEYS
    .filter(type => new RegExp(type).test(type + ''))
    .map(type => PROP_DEFAULT_VALUES[type])[0]
}

function getPropertyVal (options) {
  if (isPlainObject(options)) {
    if (hasOwn(options, 'value')) {
      return options.value
    }
    return getDefaultVal(options.type)
  }
  return getDefaultVal()
}

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);
    if (type === Boolean) {
      value = !!value;
    }
    const observer = propOptions && propOptions.observer;
fxy060608's avatar
fxy060608 已提交
566 567 568 569 570 571
    if (observer) {
      // 初始化时,异步触发 observer,否则 observer 中无法访问 methods 或其他
      setTimeout(function () {
        observe(observer, vm, value);
      }, 4);
    }
fxy060608's avatar
fxy060608 已提交
572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607
    return value
  }
  return getPropertyVal(propsOptions[key])
}

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
  }
  const propsData = vm.$options.propsData || {};

  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 已提交
608 609 610 611
        const oldVal = value;
        /* eslint-disable no-self-compare */
        if (newVal === value || (newVal !== newVal && value !== value)) {
          return
fxy060608's avatar
fxy060608 已提交
612
        }
fxy060608's avatar
fxy060608 已提交
613
        value = newVal;
fxy060608's avatar
fxy060608 已提交
614 615 616
        if (observer) {
          observe(observer, vm, newVal, oldVal);
        }
fxy060608's avatar
fxy060608 已提交
617 618
        // 触发渲染
        vm.$forceUpdate();
fxy060608's avatar
fxy060608 已提交
619 620 621 622 623 624
      }
    });
  }
}

function updateProperties (vm) {
fxy060608's avatar
fxy060608 已提交
625
  const properties = vm.$options.mpOptions && vm.$options.mpOptions.properties;
fxy060608's avatar
fxy060608 已提交
626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659
  const propsData = vm.$options.propsData;
  if (propsData && properties) {
    Object.keys(properties).forEach(key => {
      if (hasOwn(propsData, key)) {
        const type = getType(properties[key]);
        if (type === Boolean) {
          vm[key] = !!propsData[key];
        } else {
          vm[key] = propsData[key];
        }
      }
    });
  }
}

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 已提交
660
  vm.setData = setData;
fxy060608's avatar
fxy060608 已提交
661 662 663 664 665 666 667 668 669 670 671 672 673

  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 已提交
674
    };
fxy060608's avatar
fxy060608 已提交
675 676 677 678 679 680 681 682 683 684 685 686 687 688
    oldEmit.call(vm, eventName, {
      target,
      currentTarget: target,
      detail
    });
  };
  // 主要是Vant 自己封装了 $emit,放到 methods 中会触发 Vue 的警告,索性,框架直接重写该方法
  vm.$emit = (...args) => {
    vm.triggerEvent(...args);
  };
  vm.getRelationNodes = (relationKey) => {
    /* eslint-disable  no-mixed-operators */
    return vm._$relationNodes && vm._$relationNodes[relationKey] || []
  };
fxy060608's avatar
fxy060608 已提交
689 690

  vm._$updateProperties = updateProperties;
fxy060608's avatar
fxy060608 已提交
691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712
}

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 已提交
713 714 715 716
    // 取消 development 时的 Proxy,避免小程序组件模板中使用尚未定义的属性告警
    this._renderProxy = this;
  },
  created () { // properties 中可能会访问 methods,故需要在 created 中初始化
fxy060608's avatar
fxy060608 已提交
717 718 719 720 721 722 723 724 725
    initState(this);
    initMethods(this);
    initRelations(this);
  },
  mounted () {
    handleObservers(this);
  },
  beforeDestroy () {
    handleRelations(this, 'unlinked');
fxy060608's avatar
fxy060608 已提交
726 727 728
  }
};

fxy060608's avatar
fxy060608 已提交
729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746
/**
 * wxs getRegExp
 */
function getRegExp () {
  const args = Array.prototype.slice.call(arguments);
  args.unshift(RegExp);
  return new (Function.prototype.bind.apply(RegExp, args))()
}

/**
 * wxs getDate
 */
function getDate () {
  const args = Array.prototype.slice.call(arguments);
  args.unshift(Date);
  return new (Function.prototype.bind.apply(Date, args))()
}

fxy060608's avatar
fxy060608 已提交
747 748 749
global['__wxRoute'] = '';
global['__wxComponents'] = Object.create(null);
global['__wxVueOptions'] = Object.create(null);
fxy060608's avatar
fxy060608 已提交
750

fxy060608's avatar
fxy060608 已提交
751 752 753 754 755 756 757
function Page (options) {
  const pageOptions = parsePage(options);
  pageOptions.mixins.unshift(polyfill);
  pageOptions.mpOptions.path = global['__wxRoute'];
  global['__wxComponents'][global['__wxRoute']] = pageOptions;
}

fxy060608's avatar
fxy060608 已提交
758 759 760 761 762 763 764 765 766 767
function initRelationsHandler (vueComponentOptions) {
  // linked 需要在当前组件 attached 之后再执行
  if (!vueComponentOptions['onServiceAttached']) {
    vueComponentOptions['onServiceAttached'] = [];
  }
  vueComponentOptions['onServiceAttached'].push(function onServiceAttached () {
    handleRelations(this, 'linked');
  });
}

fxy060608's avatar
fxy060608 已提交
768 769 770
function Component (options) {
  const componentOptions = parseComponent(options);
  componentOptions.mixins.unshift(polyfill);
fxy060608's avatar
fxy060608 已提交
771
  componentOptions.mpOptions.path = global['__wxRoute'];
fxy060608's avatar
fxy060608 已提交
772
  initRelationsHandler(componentOptions);
fxy060608's avatar
fxy060608 已提交
773
  global['__wxComponents'][global['__wxRoute']] = componentOptions;
fxy060608's avatar
fxy060608 已提交
774 775 776 777
}

function Behavior (options) {
  return options
fxy060608's avatar
fxy060608 已提交
778 779 780
}

const nextTick = Vue.nextTick;
fxy060608's avatar
fxy060608 已提交
781

fxy060608's avatar
fxy060608 已提交
782 783
export default uni;
export { Behavior, Component, Page, getDate, getRegExp, nextTick };