虚拟dom及diff算法之 —— snabbdom

源码:https://github.com/snabbdom/snabbdom

测试环境搭建

npm i -S snabbdom

安装好的node_modules提供了js和ts的代码:build:js代码,src:ts代码
npm i -D webpack@5 webpack-cli@3 webpack-dev-server@3
webpack:构建工具,必须安装5版本的,因为5版本才支持exports导出的能力

webpack-dev-server:提供8080端口访问
package.json中配置运行文件的入口

javascript 复制代码
"scripts": {
 "dev": "webpack-dev-server"
},

www/index.html

javascript 复制代码
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <!-- src/index.js中需要一个container容器 -->
    <div id="container">你好</div>
    <script src="/xuni/bundle.js"></script>
  </body>
</html>

src/index.js

javascript 复制代码
// 官方demo,参照https://github.com/snabbdom/snabbdom配置
import { init, classModule, propsModule, styleModule, eventListenersModule, h } from 'snabbdom'

const patch = init([
  // Init patch function with chosen modules
  classModule, // makes it easy to toggle classes
  propsModule, // for setting properties on DOM elements
  styleModule, // handles styling on elements with support for animations
  eventListenersModule // attaches event listeners
])

const container = document.getElementById('container')

const vnode = h('div#container.two.classes', { on: { click: () => console.log('div clicked') } }, [
  h('span', { style: { fontWeight: 'bold' } }, 'This is bold'),
  ' and this is just normal text',
  h('a', { props: { href: '/foo' } }, "I'll take you places!")
])
// Patch into empty DOM element -- this modifies the DOM as a side effect
patch(container, vnode)

const newVnode = h('div#container.two.classes', { on: { click: () => console.log('updated div clicked') } }, [
  h('span', { style: { fontWeight: 'normal', fontStyle: 'italic' } }, 'This is now italic type'),
  ' and this is still just normal text',
  h('a', { props: { href: '/bar' } }, "I'll take you places!")
])
// Second `patch` invocation
patch(vnode, newVnode) // Snabbdom efficiently updates the old view to the new state

运行:yarn dev
访问:http://localhost:8080/

相关推荐
前端极客探险家2 小时前
前端 Excel 工具组件实战:导入 → 可编辑表格 → 导出 + 样式同步 + 单元格合并
前端·typescript·vue·excel
有什么东东18 小时前
山东大学软件学院创新项目实训开发日志(20)之中医知识问答自动生成对话标题bug修改
java·vue·bug·springboot
络718 小时前
IDEA导入并启动若依项目步骤(SpringBoot+Vue3)
java·spring boot·mysql·vue·intellij-idea
脑瓜嗡3 天前
发送百度地图的定位
vue·php
巴啦啦臭魔仙3 天前
buildadmin 自定义单元格渲染
vue·php
小贺要学前端3 天前
前端如何优雅地对接后端
前端·性能优化·vue·前端优化
凕雨3 天前
Cesium学习笔记——坐标系统及坐标转换
前端·javascript·笔记·学习·arcgis·vue
前端极客探险家4 天前
打造一个 AI 面试助手:输入岗位 + 技术栈 → 自动生成面试问题 + 标准答案 + 技术考点图谱
前端·人工智能·面试·职场和发展·vue
末日的狂欢姐4 天前
AXUI - 极致原生体验的零依赖的国产 Web UI 框架,欢迎体验和共建!
javascript·前端框架·vue·网站建设·ui设计