虚拟DOM和diff算法(二) h函数

136 阅读1分钟

虚拟DOM

用Javascript对象描述DOM的层次结构。DOM中的一切都在虚拟DOM中对应的属性。

新虚拟DOM和老虚拟DOM进行diff(精细化比较),算出应该如何最小量更新,最后反映到真正的DOM上

h函数,产生虚拟节点(vnode)

h(“p”, { style: “color:red” }, “小米mix4性价比一般啊?”)

  • 参数一:标签名,字符串
  • 参数二:对象(props,properties)、或者数组
  • 参数三:内容

全部元素

  • sel 元素选择器
  • data 元素属性
  • children 元素子节点 (可以没有)
  • text 元素文本
  • elm 对应dom元素 (没有则没有上dom树)1
  • key

patch函数让虚拟节点上树

import { h } from 'snabbdom/h'

const patch = init([
  classModule, // 切换类的模块
  propsModule, // 设置DOM元素属性的模块
  styleModule, // 设置行内样式或动画的模块
  eventListenersModule, // 事件监听模块
])


const container = document.getElementById("container");
// 嵌套使用
const vnode_p = h('ul', {}, [
  h('li''威马'),
  h('li'h('strong','出了车祸')),
  h('li'h('a', {
    props: {
      'href''http://www.byd.com'
    }
  },['比亚迪对撞'h('strong', {}, '极狐')]))
])
const vnode_a = h('a', {
  'props': {
    'href''https://www.bing.com',
    'target':'_blank'
}},'来看看今天的桌面');

console.log(JSON.stringify(vnode_p))

// 虚拟节点上dom树
patch(container, vnode_p);

{"sel":"ul","data":{},"children":[{"sel":"li","data":{},"text":"威马"},{"sel":"li","data":{},"children":[{"sel":"strong","data":{},"text":"出了车祸"}]},{"sel":"li","data":{},"children":[{"sel":"a","data":{"props":{"href":"www.byd.com"}},"children":[{"text":"比亚迪对撞"},{"sel":"strong","data":{},"text":"极狐"}]}]}]}

函数重载

./src/h.ts

export function h(sel: string): VNode;
export function h(sel: string, data: VNodeData): VNode;
export function h(sel: string, children: VNodeChildren): VNode;
export function h(sel: string, data: VNodeData, children: VNodeChildren): VNode;
export function h(sel: any, b?: any, c?: any): VNode {}