Vue Render函數(shù)原理及代碼實例解析
簡單的說,在vue中我們使用模板HTML語法組建頁面的,使用render函數(shù)我們可以用js語言來構(gòu)建DOM
因為vue是虛擬DOM,所以在拿到template模板時也要轉(zhuǎn)譯成VNode的函數(shù),而用render函數(shù)構(gòu)建DOM,vue就免去了轉(zhuǎn)譯的過程。
當(dāng)使用render函數(shù)描述虛擬DOM時,vue提供一個函數(shù),這個函數(shù)是就構(gòu)建虛擬DOM所需要的工具。官網(wǎng)上給他起了個名字叫createElement。還有約定的簡寫叫h
雖然在render里使用createElement函數(shù)創(chuàng)建DOM節(jié)點不是很直觀,但是在部分獨立組件的設(shè)計中還是可以滿足一些特殊需求的。一個簡單的render示例如下:
<!DOCTYPE html><html lang='zh-CN'><head> <meta charset='UTF-8'> <meta name='viewport' content='width=device-width, initial-scale=1.0'> <meta http-equiv='X-UA-Compatible' content='ie=edge'> <title>Document</title></head><body> <div id='app'> <my-component :list='list'></my-component> </div> <script src='http://www.piao2010.com/bcjs/vue.js'></script> <script> Vue.component(’my-component’, { props: {list: { type: Array, default: () => []} }, render(createElement) {if (this.list.length) { return createElement(’ul’, this.list.map(item => createElement(’li’, item)))} else { return createElement(’p’, ’Empty list’)} } }) new Vue({ el: ’#app’, data: {list: [’html’, ’css’, ’javascript’] } }) </script></body></html>
另外,由于v-if,v-else,v-show等指令都無法在render里使用,需要自己手動實現(xiàn),拿常用的v-model舉個栗子:
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
Vue.component(’my-component’, { data() { return { message: ’’ } }, render(createElement) { return createElement( ’div’, [createElement( ’input’, { on: { input: e => this.message = e.target.value } }),createElement(’p’, this.message) ] ) }})
相關(guān)文章:
1. 使用Docker的NFS-Ganesha鏡像搭建nfs服務(wù)器的詳細(xì)過程2. Django使用HTTP協(xié)議向服務(wù)器傳參方式小結(jié)3. 刪除docker里建立容器的操作方法4. Docker 部署 Prometheus的安裝詳細(xì)教程5. VMware中如何安裝Ubuntu6. IntelliJ IDEA導(dǎo)入jar包的方法7. IntelliJ IDEA恢復(fù)刪除文件的方法8. 使用 kind 和 Docker 啟動本地的 Kubernetes環(huán)境9. docker /var/lib/docker/aufs/mnt 目錄清理方法10. IntelliJ IDEA配置Tomcat服務(wù)器的方法
