生命周期的合并

1.Mixin原理

  1. import {mergeOptions} from '../util/index.js'
  2. export function initGlobalAPI(Vue){
  3. Vue.options = {};
  4. Vue.mixin = function (mixin) {
  5. // 将属性合并到Vue.options上
  6. this.options = mergeOptions(this.options,mixin);
  7. return this;
  8. }
  9. }

2.合并生命周期

  1. export const LIFECYCLE_HOOKS = [
  2. 'beforeCreate',
  3. 'created',
  4. 'beforeMount',
  5. 'mounted',
  6. 'beforeUpdate',
  7. 'updated',
  8. 'beforeDestroy',
  9. 'destroyed',
  10. ]
  11. const strats = {};
  12. function mergeHook(parentVal, childValue) {
  13. if (childValue) {
  14. if (parentVal) {
  15. return parentVal.concat(childValue);
  16. } else {
  17. return [childValue]
  18. }
  19. } else {
  20. return parentVal;
  21. }
  22. }
  23. LIFECYCLE_HOOKS.forEach(hook => {
  24. strats[hook] = mergeHook
  25. })
  26. export function mergeOptions(parent, child) {
  27. const options = {}
  28. for (let key in parent) {
  29. mergeField(key)
  30. }
  31. for (let key in child) {
  32. if (!parent.hasOwnProperty(key)) {
  33. mergeField(key);
  34. }
  35. }
  36. function mergeField(key) {
  37. if (strats[key]) {
  38. options[key] = strats[key](parent[key], child[key]);
  39. } else {
  40. if (typeof parent[key] == 'object' && typeof child[key] == 'object') {
  41. options[key] = {
  42. ...parent[key],
  43. ...child[key]
  44. }
  45. }else{
  46. options[key] = child[key];
  47. }
  48. }
  49. }
  50. return options
  51. }

4.调用生命周期

  1. export function callHook(vm, hook) {
  2. const handlers = vm.$options[hook];
  3. if (handlers) {
  4. for (let i = 0; i < handlers.length; i++) {
  5. handlers[i].call(vm);
  6. }
  7. }
  8. }

5.初始化流程中调用生命周期

init.js

  1. Vue.prototype._init = function (options) {
  2. const vm = this;
  3. vm.$options = mergeOptions(vm.constructor.options,options);
  4. // 初始化状态
  5. callHook(vm,'beforeCreate');
  6. initState(vm);
  7. callHook(vm,'created');
  8. if (vm.$options.el) {
  9. vm.$mount(vm.$options.el);
  10. }
  11. }