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

相关推荐
G探险者3 小时前
聊一聊vue如何实现角色权限的控制的
vue
Pro_er7 小时前
深入浅出 Vue3:组件与模板基础全解析
vue·前端开发
寰宇软件10 小时前
PHP图书借阅小程序
小程序·uni-app·vue·php
.NET快速开发框架19 小时前
使用nvm管理node.js版本,方便vue2,vue3开发
vue·.netcore·常用工具·开发技术·rdif
Pro_er2 天前
Vue3 基础概念与环境搭建
vue·前端开发
万象工作室3 天前
【开源项目】数字孪生武汉~超经典智慧城市CIM/BIM数字孪生可视化项目——开源工程及源码
vue.js·人工智能·信息可视化·云计算·vue·智慧城市·数据可视化
西门吹雪~3 天前
【前端框架】Vue3 面试题深度解析
前端·前端框架·vue·vue3·前端面试
寰宇软件4 天前
PHP在线题库小程序
小程序·uni-app·vue·php
Pro_er4 天前
《Vue2 框架第二课:组件结构与模板语法详解》
vue·前端开发
小晗同学5 天前
小程序canvas2d实现横版全屏和竖版逐字的签名组件(字帖式米字格签名组件)
小程序·uni-app·vue·手写签名·canvas2d