首页 > 编程语言 >Vue源码解析——虚拟DOM和diff算法

Vue源码解析——虚拟DOM和diff算法

时间:2022-09-22 17:33:30浏览次数:60  
标签:Vue undefined DOM vnode 源码 div sel data children

前置环境:

1. 手写h函数

  • vnode.js
// 默认暴露
export default function(sel, data, children, text, elm) {
  return { sel, data, children, text, elm }
}
  • h.js
import vnode from './vnode'

// 本例实现必须传3个参数的h函数
// 1. h('div', {}, '文字')
// 2. h('div', {}, [])
// 3. h('div', {}, h())

export default function (sel, data, c) {
  if (arguments.length != 3) {
    throw new Error('h函数必须传入3个参数')
  }
  if (typeof c == 'string' || typeof c == 'number') {
    // 1 ===============
    return vnode(sel, data, undefined, c, undefined)
  } else if(Array.isArray(c)) {
    // 2 ===============
    let children = []      
    c.forEach(item => {
      if (!(typeof item == 'object' && item.hasOwnProperty('sel'))) throw new Error('传入的数组参数中有不是h函数的项')
      children.push(item)
    });
    return vnode(sel, data, children, undefined, undefined)
  } else if(typeof c == 'object' && c.hasOwnProperty('sel')) {
    // 3 ===============
    let children = [c]
    return vnode(sel, data, children, undefined, undefined)
  } else {
    throw new Error('传入的第三个参数类型错误')
  }
}
  • index.js
import h from './mysnabbdom/h'

var myVnode1 = h('div', {}, '文字')
var myVnode2 = h('div', {}, [
  h('p', {}, '哈哈'),
  h('p', {}, '嘻嘻'),
  h('p', {}, '呵呵'),
  h('p', {}, [
    h('span', {}, 'A'),
    h('span', {}, 'B')
  ]),
])
var myVnode3 = h('div', {}, h('span', {}, '我是span'))

console.log(myVnode1);
console.log(myVnode2);
console.log(myVnode3);
  • index.html
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <div id="container"></div>
  <!-- 引入虚拟打包文件 -->
  <script src="/xuni/bundle.js"></script>
</body>
</html>

 

2. patch函数

 

标签:Vue,undefined,DOM,vnode,源码,div,sel,data,children
From: https://www.cnblogs.com/suihung/p/16710407.html

相关文章