網(wǎng)頁設(shè)計(jì)教程孟憲寧課后題答案seo實(shí)戰(zhàn)培訓(xùn)王乃用
使用js對象來描述UI更加的靈活?!斑@種對象”在vue框架中被稱為虛擬DOM,渲染函數(shù)內(nèi)部可以創(chuàng)建虛擬DOM,然后vue.js可以將其內(nèi)容進(jìn)行渲染。
1.渲染器的介紹
渲染器的作用就是把虛擬DOM渲染為真實(shí)DOM
思考下,我們有一個虛擬 DOM,如何將它轉(zhuǎn)換為真實(shí) DOM
const vnode = {tag: 'div',props: {onClick: () => alert('hello')},children: 'click me'
}
2.實(shí)現(xiàn)渲染函數(shù)renderer(只考慮創(chuàng)建沒有考慮更新邏輯情況下)
-
兩個參數(shù)。參數(shù)vnode表示虛擬 DOM 對象,container表示一個真實(shí) DOM 元素,作為掛載點(diǎn),渲染器會把虛擬 DOM 渲染到該掛載點(diǎn)
-
使用vnode.tag作為創(chuàng)建的dom標(biāo)簽el
-
遍歷vnode.props,將屬性 事件添加到DOM上(事件即給元素添加監(jiān)聽事件;)
-
處理 children(如果 children 是字符串,說明它是元素的文本子節(jié)點(diǎn)用createTextNode;如果children是數(shù)組則遞歸調(diào)用render函數(shù)渲染子節(jié)點(diǎn)并掛載到el元素下)
-
將元素添加到掛載節(jié)點(diǎn)container下
<div id="app"></div><script>// 手寫render函數(shù)將自己定義的vnode對象渲染到頁面/*** @vnode 虛擬 DOM 對象* @container 一個真實(shí) DOM 元素,作為掛載點(diǎn),渲染器會把虛擬 DOM 渲染到該掛載點(diǎn)*/function render(vnode, container) {// 使用vnode.tag作為創(chuàng)建的dom標(biāo)簽ellet el = document.createElement(vnode.tag);// 遍歷vnode.props,將屬性 事件添加到DOM上(事件即給元素添加監(jiān)聽事件;)for (let key in vnode.props) {// 判斷如果為事件則將其設(shè)置到el中if ((/^(on)/).test(key)) {el.addEventListener(key.substr(2).toLowerCase(), vnode.props[key]);}}// 處理 children(字符串和數(shù)組)if (typeof vnode.children === "string") {el.appendChild(document.createTextNode(vnode.children));} else if (Array.isArray(vnode.children)) { //是數(shù)組進(jìn)行遍歷并遞歸調(diào)用render方法vnode.children.forEach(child => {render(child, el);});}// 將元素添加到掛載節(jié)點(diǎn)container下container.appendChild(el);}// render函數(shù)測試const container = document.getElementById('app')const vnode = {tag: 'div',props: {onClick: () => alert('hello')},// children: 'click me'children: [{tag: 'h1',props: {onClick: () => alert('h1')},children: '這是h1'},{tag: 'span',props: {onClick: () => alert('span')},children: '這是span'}]}render(vnode, container)</script>