虚拟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/

相关推荐
狼性书生7 小时前
uniapp实现的简约美观的星级评分组件
前端·uni-app·vue·组件
宇宙的最后一粒尘埃17 小时前
Typeerror: cannot read properties of undefined (reading ‘XXX‘)
vue
清幽竹客1 天前
vue-18(使用 Vuex 插件实现高级功能)
前端·vue.js·前端框架·vue
牧码岛1 天前
Web前端之隐藏元素方式的区别、Vue循环标签的时候在同一标签上隐藏元素的解决办法、hidden、display、visibility
前端·css·vue·html·web·web前端
MINO吖2 天前
基于 qiankun + vite + vue3 构建微前端应用实践
vue·vite·微前端·qiankun·single-spa
Luffe船长2 天前
elementUI点击浏览table所选行数据查看文档
javascript·elementui·vue
IT瘾君2 天前
JavaWeb:前端工程化-ElementPlus
前端·elementui·node.js·vue
sunbyte3 天前
50天50个小项目 (Vue3 + Tailwindcss V4) ✨ | Dad Jokes(冷笑话卡片)
前端·javascript·css·vue.js·vue
幽络源小助理4 天前
SpringBoot+Vue+微信小程序校园自助打印系统
java·spring boot·微信小程序·小程序·vue
霸王蟹6 天前
从前端工程化角度解析 Vite 打包策略:为何选择 Rollup 而非 esbuild。
前端·笔记·学习·react.js·vue·rollup·vite