mini-vue: 响应式数据的实现

在单文件中实现所有逻辑
index.html

<div id="app"></div>
<script>
  function h(tag, props, children) {
    return {
      tag,
      props,
      children,
    }
  }

  function render(vnode) {
    const el = document.createElement(vnode.tag)
    if (vnode.props) {
      for (key in vnode.props) {
        const value = vnode.props[key]
        if (key.startsWith('on')) {
          el.addEventListener(key.slice(2).toLowerCase(), value)
        } else {
          el.setAttribute(key, value)
        }
      }
    }
    if (vnode.children) {
      if (typeof vnode.children === 'string') {
        el.innerHTML = vnode.children
      } else {
        vnode.children.forEach((child) => {
          mount(child, el)
        })
      }
    }
    return el
  }

  function mount(vnode, container) {
    if (typeof container === 'string') {
      container = document.querySelector(container)
    }
    const el = render(vnode)
    vnode.el = el
    container.appendChild(el)
  }

  function patch(n1, n2) {
    if (n1.tag === n2.tag) {
      const el = (n2.el = n1.el)
      //props
      const oldProps = n1.props || {}
      const newProps = n2.props || {}
      for (const key in newProps) {
        const oldValue = oldProps[key]
        const newValue = newProps[key]
        if (newValue !== oldValue) {
          el.setAttribute(key, newValue)
        }
      }
      for (const key in oldProps) {
        if (!(key in newProps)) {
          el.removeAttribute(key)
        }
      }

      //children
      const oldChildren = n1.children
      const newChildren = n2.children
      if (typeof newChildren === 'string') {
        el.textContent = newChildren
      } else {
        if (typeof oldChildren === 'string') {
          el.innerHTML = ''
          newChildren.forEach((child) => {
            mount(child, el)
          })
        } else {
          const commonLength = Math.min(oldChildren.length, newChildren.length)
          for (let i = 0; i < commonLength; i++) {
            patch(oldChildren[i], newChildren[i])
          }
          if (newChildren.length > oldChildren.length) {
            newChildren.slice(commonLength).forEach((child) => {
              mount(child, el)
            })
          } else if (newChildren.length < oldChildren.length) {
            oldChildren.slice(commonLength).forEach((child) => {
              el.removeChild(child.el)
            })
          }
        }
      }
    } else {
      // replace
    }
  }

  // reactivity part
  let activeEffect
  class Dep {
    subscribers = new Set()
    depend() {
      if (activeEffect) {
        this.subscribers.add(activeEffect)
      }
    }
    notify() {
      this.subscribers.forEach((effect) => {
        effect()
      })
    }
  }
  function watchEffect(effect) {
    activeEffect = effect
    effect()
    activeEffect = null
  }

  const targetMap = new WeakMap()

  function getDep(target, key) {
    let depsMap = targetMap.get(target)
    if (!depsMap) {
      depsMap = new Map()
      targetMap.set(target, depsMap)
    }
    let dep = depsMap.get(key)
    if (!dep) {
      dep = new Dep()

      depsMap.set(key, dep)
    }
    return dep
  }

  const reactiveHandlers = {
    get(target, key, receiver) {
      const dep = getDep(target, key)
      dep.depend()
      return Reflect.get(target, key, receiver)
    },
    set(target, key, value, receiver) {
      const dep = getDep(target, key)
      const result = Reflect.set(target, key, value, receiver)
      dep.notify()
      return result
    },
  }

  function reactive(raw) {
    return new Proxy(raw, reactiveHandlers)
  }

  function mountApp(component, container) {
    let isMounted = false
    let prevVdom
    watchEffect(() => {
      const newVdom = component.render()
      if (!isMounted) {
        mount(newVdom, container)
        prevVdom = newVdom
        isMounted = true
      } else {
        patch(prevVdom, newVdom)
        prevVdom = newVdom
      }
    })
  }

  const App = {
    data: reactive({
      count: 0,
    }),
    render() {
      return h(
        'div',
        {
          onClick: () => {
            this.data.count++
          },
        },
        String(this.data.count)
      )
    },
  }

  mountApp(App, '#app')
</script>
posted @ 2024-02-28 00:30  HorseShoe2016  阅读(2)  评论(0编辑  收藏  举报