Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

12 实现组件2 #14

Open
xwjie opened this issue Jan 15, 2018 · 0 comments
Open

12 实现组件2 #14

xwjie opened this issue Jan 15, 2018 · 0 comments

Comments

@xwjie
Copy link
Owner

xwjie commented Jan 15, 2018

实现组件注册功能

关键点,使用 extends 继承 Xiao , 在构造方法 constructor 里面调用 super(definition)

class Xiao{
   /**
   * 全局注册组件
   */
  static component(id: string, definition?: Object) {
    if (globalComponent[id]) {
      return globalComponent[id]
    }

    if (!definition) {
      return null
    }

    const newClass = class extends Xiao {
      constructor() {
        super(definition)
      }
    }

    for (let key in definition) {
      newClass[key] = definition[key]
    }

    globalComponent[id] = newClass
    log('globalComponent', globalComponent)

    return newClass
  }
}

给虚拟节点增加 insert hook

insert 钩子里面,调用 子组件的 $mount 函数,渲染dom。

function setComponentHook(vnode: any, vm: Xiao) {
  if (!vnode.sel) {
    return
  }

  // 查看是否组成了组件?
  const Comp = Xiao.component(vnode.sel)

  if (Comp) {
    log('组件', Comp)

    vnode.data.hook = {
      insert: (vnode) => {
        log('component vnode', vnode)

        let app =new Comp()
        app._parent = vm

        app.$mount(vnode.elm)
      }
    }
  }

  if (vnode.children) {
    vnode.children.forEach(function (e) {
      setComponentHook(e, vm)
    }, this)
  }

}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant