Vue 2 인스턴스 초기화 과정

Vue 2의 인스턴스 생성 및 초기화는 여러 단계로 구성되며, 각 단계에서 특정 기능이 설정됩니다.

1. 인스턴스 생성 진입점

Vue 인스턴스는 생성자 함수를 통해 시작되며, 내부적으로 _init 메서드를 호출합니다.

function Vue(config) {
  this._init(config);
}

2. 핵심 초기화 로직

2.1 _init 메서드

이 메서드는 Vue 인스턴스의 기본 구조와 상태를 설정하는 중심 역할을 합니다.

Vue.prototype._init = function(config) {
  const instance = this;

  // 옵션 병합
  if (config && config._isComponent) {
    setupComponentOptions(instance, config);
  } else {
    instance.$options = combineOptions(
      getBaseOptions(instance.constructor),
      config || {},
      instance
    );
  }

  // 라이프사이클 관련 속성 초기화
  setupLifecycle(instance);
  setupEventHandlers(instance);
  setupRenderer(instance);
  triggerHook(instance, 'beforeCreate');
  setupInjection(instance);
  initializeState(instance);  // 상태 관리 시스템 설정
  setupProvide(instance);
  triggerHook(instance, 'created');

  // DOM에 마운트
  if (instance.$options.el) {
    instance.$mount(instance.$options.el);
  }
};

2.2 상태 시스템 초기화

Vue의 반응형 시스템은 이 단계에서 구성 요소들을 초기화하면서 구축됩니다.

function initializeState(instance) {
  instance._watchers = [];
  const settings = instance.$options;

  if (settings.props) configureProps(instance, settings.props);
  if (settings.methods) bindMethods(instance, settings.methods);
  if (settings.data) {
    prepareData(instance); // 데이터 반응형 처리
  } else {
    observe(instance._data = {}, true);
  }
  if (settings.computed) defineComputed(instance, settings.computed);
  if (settings.watch) createWatchers(instance, settings.watch);
}

2.3 데이터 반응형 처리

function prepareData(instance) {
  let source = instance.$options.data;
  source = instance._data = typeof source === 'function'
    ? executeDataFn(source, instance)
    : source || {};

  // 데이터 프록시 설정
  const keys = Object.keys(source);
  for (let i = 0; i < keys.length; i++) {
    linkProperty(instance, '_data', keys[i]);
  }

  // 반응형 감지 시작
  observe(source, true);
}

3. 템플릿 렌더링 준비

3.1 $mount 구현

DOM에 컴포넌트를 연결하기 전에 템플릿을 렌더 함수로 변환합니다.

Vue.prototype.$mount = function(element, hydrateMode) {
  element = element && getElement(element);

  const config = this.$options;
  if (!config.render) {
    let templateContent = config.template;
    if (templateContent) {
      const compiled = compileTemplate(templateContent, { ... });
      config.render = compiled.render;
      config.staticRenderFns = compiled.staticRenderFns;
    }
  }

  return originalMount.call(this, element, hydrateMode);
};

4. 전체 초기화 순서

  1. 옵션 통합: 클래스 수준과 인스턴스 수준의 설정을 병합
  2. 라이프사이클 설정: 부모-자식 관계 및 생명주기 변수 초기화
  3. 이벤트 시스템: 상위 컴포넌트로부터 받은 이벤트 바인딩
  4. 렌더링 준비: 슬롯 정보 및 createElement 함수 정의
  5. beforeCreate 훅 실행
  6. 의존성 주입: inject 옵션 처리
  7. 상태 시스템 구성:
    • props 처리
    • methods 바인딩
    • data 반응형 등록
    • computed 속성 정의
    • watcher 등록
  8. 제공자 설정: provide 옵션 적용
  9. created 훅 실행
  10. 엘리먼트 마운트: el 옵션이 존재하면 자동으로 DOM에 연결

이러한 일련의 과정을 거치면서 Vue 인스턴스는 완전한 반응형 시스템을 갖추게 되며, 이후의 데이터 변경 감지와 UI 업데이트가 가능해집니다.

태그: Vue.js Vue2 reactivity component-lifecycle javascript-framework

7월 14일 18:32에 게시됨