init函数
init函数返回值为patch函数,init是一个高阶函数
let patch = init([])
import {h, init} from 'snabbdom'// init函数的返回值,是一个patch函数,作用是对比两个vnode的差异,更新到真实domlet patch = init([])// h函数的作用是生成虚拟dom,用法,第一个参数:标签+选择器// 第二个参数:如果是字符串,就是标签中的内容let vnode = h("div#container", "hello world" )let app = document.querySelector("#app")/*patch函数的作用,通过对比vnode,是否更新第一个参数可以是dom元素,内部把dom转化为虚拟vnode第二个参数,新的vnode返回值:vnode,更新视图*/let oldNnode = patch(app, vnode)// 新创建的vnode,会替换原来的container节点vnode = h("div#change", "hello snabbdom")patch(oldNnode, vnode)
h函数
h函数将dom生成虚拟节点vnode,最开始使用的hyperScript写的方法,所以使用h作为开头。
let vnode = h("div#container",[h("h1", "this is h1"),h("h2", "this is h2"),h("p", "这是通过h函数创建的虚拟节点node")])
模块化
常用模块:
attributes
设置dom元素的属性,使用setAttribute()
props
和attributes模块类似,设置dom元素属性element[attr] = value;
class
切换类样式,通过sel选择器给元素设置类样式
dataset
设置data-*自定义属性
eventlisteners
注册和移除事件
style
使用模块步骤:
1.导入需要的模块
2.init中注册模块
3.使用h函数创建vnode时,可以把第二个参数设置为模块对象,其他参数后移import {h, init, styleModule, eventListenersModule} from "snabbdom"/* snabbdom核心代码不能处理属性/事件/样式,如果需要处理,可以使用模块*/// 注册模块let patch = init([styleModule, eventListenersModule])let vnode = h("div.container", {style:{color:"blue",backgroundColor:"#e1e1e1",padding: "10px"},on:{click:clickHandler}},[h("h1", "这是使用模块创建的vnode"),h("p", "使用了style和eventlistener模块")])function clickHandler(){console.log("clickHandler");}let app = document.querySelector("#app");patch(app, vnode)
