浠庡ご鍒涘缓鎮ㄨ嚜宸辩殑vue.js鈥斺€旂2閮ㄥ垎(铏氭嫙DOM鍩虹)
Posted 浜虹敓浠g爜
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了浠庡ご鍒涘缓鎮ㄨ嚜宸辩殑vue.js鈥斺€旂2閮ㄥ垎(铏氭嫙DOM鍩虹)相关的知识,希望对你有一定的参考价值。
杩欐槸鈥滀粠澶村垱寤鸿嚜宸辩殑vuei .js鈥濈郴鍒楁枃绔犵殑绗簩閮ㄥ垎锛屽湪杩欓噷鎴戝皢浠嬬粛濡備綍鍒涘缓鍝嶅簲寮忔鏋?姣斿vuei .js)鐨勫熀鏈師鐞嗐€傚湪绗竴閮ㄥ垎涓紝鎴戞弿杩颁簡鎴戜滑闇€瑕佺殑閮ㄥ垎鍜岃閬靛惊鐨勮矾绾垮浘銆傚鏋滀綘杩樻病鏈夎杩囷紝鎴戝缓璁綘鍦ㄩ槄璇昏繖绡囨枃绔犱箣鍓嶅厛璇讳竴涓嬨€?/p>
What is a virtual DOM?
馃挕DOM鏂囨。瀵硅薄妯″瀷,涓€涓綉绔欑殑HTML缁撴瀯 馃挕VDOM =浠h〃缁撴瀯鐨勫壇鏈?/p>
铏氭嫙DOM鏄皢瀹為檯DOM琛ㄧず涓篔avaScript鏍煎紡锛屽湪杩欑鏍煎紡涓搷浣滃畠姣斿湪姣忔鏈夊彉鍖栨椂鎿嶄綔瀹為檯DOM鏇村鏄撱€佹垚鏈洿浣庛€?/p>
濡傛灉鎮ㄤ笉鎯冲皢DOm鍛堢幇缁欐祻瑙堝櫒锛岃€屾槸鍛堢幇缁欎竴涓瓧绗︿覆(褰撴秹鍙婂埌鏈嶅姟鍣ㄧ鍛堢幇鏃跺緢鏂逛究)锛岄偅涔堝畠涔熷緢鏈夌敤銆?/p>
Virtual nodes
鎵€浠ワ紝铏氭嫙DOM鏄敱铏氭嫙鑺傜偣缁勬垚鐨勶紝鍦ㄦ垜浠皢瑕佺紪鐮佺殑渚嬪瓙涓紝瀹冪湅璧锋潵鏄繖鏍风殑:
{
tag: 'div',
props: {
class: 'container'
},
children: [
{
tag: 'h1',
props: {},
children: 'Hello World'
},
{
tag: 'p',
props: {},
children: 'Lorem ipsum dolor sit amet.'
}
]
}
涓婇潰鐨勪緥瀛愮浉褰撲簬杩欎釜html浠g爜:
<div class="container">
<h1>Hello World</h1>
<p>Lorem ipsum dolor sit amet.</p>
</div>
鎵€浠ヤ竴涓櫄鎷熻妭鐐圭殑缁勬垚涓?
-
An HTML tag as String -
An Object of properties -
A list of children than can either be: -
Another node -
A text (representing the content)
Virtual DOM skeleton
鍦ㄦ垜浠殑绀轰緥涓紝鎴戜滑灏嗕笉鏋勫缓涓€涓垚鐔熺殑铏氭嫙DOM鈥滃紩鎿庘€濓紝浣嗚冻浠ョ悊瑙e熀纭€鐭ヨ瘑銆?/p>
璁╂垜浠湅涓€涓嬭櫄鎷烡OM鐨勭紪鐮併€傛垜浠皢鎶婃墍鏈夋湭鏉ョ殑浠g爜寤虹珛鍦ㄤ互涓嬪嚑琛屼箣涓娿€傚洜姝わ紝鍒涘缓涓€涓寘鍚互涓嬪唴瀹圭殑html鏂囦欢:
<div id="app"></app>
<script>
// Create virtual node
function h(tag, props, children) {
// Return the virtual node
}
// Mount a virtual node to the DOM
function mount(vnode, container) {
// Create the element
// Set props
// Handle children
// Mount to the DOM
}
// Unmount a virtual node from the DOM
function unmount(vnode) {
// Unmount the virtual node
}
// Take 2 vnodes, compare & figure out what's the difference
function patch(n1, n2) {
// Case where the nodes are of the same tag
// Case where the new vnode has string children
// Case where the new vnode has an array of vnodes
// Case where the nodes are of different tags
}
function render(message) {
// Render a virtual node with a given message
}
// Create virtual nodes & render them below this line...
</script>
姝e浣犳墍鐪嬪埌鐨勶紝鎴戜滑鏈変簲涓笉鍚岀殑鍑芥暟锛屽畠浠兘瀹屾垚浜嗗垱寤哄拰娓叉煋铏氭嫙DOM鐨勪换鍔?
-
h鍒涘缓涓€涓櫄鎷熻妭鐐?浣嗚繕娌℃湁灏嗗叾鎸傝浇鍒板疄闄呯殑DOM)銆傛垜绉板畠涓篽锛屽洜涓哄畠鍦╲uy銆俲s椤圭洰涓篃鏄繖鏍峰彨鐨?/p>
-
mount灏嗚幏鍙栦竴涓粰瀹氱殑铏氭嫙鑺傜偣骞跺皢鍏舵寕杞藉埌瀹為檯DOM涓殑涓€涓粰瀹氬鍣ㄤ腑銆傚浜庣涓€涓厓绱狅紝杩欏皢鏄垜浠湪鏂囦欢鏈€椤堕儴鍒涘缓鐨?app鑺傜偣銆?/p>
-
鍗歌浇灏嗕粠鐖惰妭鐐瑰垹闄よ櫄鎷熻妭鐐?/p>
-
鍒扮洰鍓嶄负姝紝patch鏄垜浠负VDOM缂栧啓鐨勬渶澶х殑鍑芥暟銆傝繖鏄洜涓烘垜浠繀椤荤敤閫掑綊鐨勬柟寮忔瘮杈冧袱涓笉鍚岀殑鑺傜偣骞舵鏌ユ墍鏈夌殑宸紓(閫掑綊鍦板鎵€鏈夌殑瀛愯妭鐐硅繘琛屾鏌?銆?/p>
-
render鏄痳ender鍑芥暟鐨勭畝鍖栫増鏈€傚湪鎴戜滑鐨勭ず渚嬩腑锛屽畠浣跨敤鍐呴儴缁欏畾鐨勬秷鎭垱寤哄悇绉嶈櫄鎷熻妭鐐?绋嶅悗鎴戜滑灏嗗鍏惰繘琛屾洿鏀癸紝浠ユ紨绀烘垜浠殑VDOM鈥滃紩鎿庘€濈殑宸ヤ綔鏂瑰紡)銆?/p>
What's next 鈿★笍
鍦ㄧ1閮ㄥ垎涓紝鎴戜滑鐪嬪埌浜嗘瀯寤鸿嚜宸辩殑Vue鎵€闇€鐨勬瀯寤洪儴鍒嗐€傚湪鏈儴鍒嗕腑锛屾垜浠簡瑙d簡濡備綍鏋勫缓铏氭嫙dom鐨勫熀纭€鐭ヨ瘑銆?/p>
鍦ㄤ笅涓€绔犱腑锛屾垜浠皢瀹為檯瀹炵幇瀹屾暣鐨勮櫄鎷烡OM閮ㄥ垎銆?/p>
以上是关于浠庡ご鍒涘缓鎮ㄨ嚜宸辩殑vue.js鈥斺€旂2閮ㄥ垎(铏氭嫙DOM鍩虹)的主要内容,如果未能解决你的问题,请参考以下文章