Render函数渲染页面
Render是使用js的完全編程能力來渲染頁面,即用js來構(gòu)建DOM.
說明:render是一個方法,自帶一個形參createElement(還有context..),這個參數(shù)也是一個方法,是用來創(chuàng)建虛擬dom節(jié)點(diǎn)的,也就是html模板的,然后渲染(render)到指定的節(jié)點(diǎn)上。render函數(shù)的目的是創(chuàng)建虛擬dom節(jié)點(diǎn)。因為createElement是個形參,所以這個形參可以用任何字符替換,比如h
- createElement/h:
createElement接收3個參數(shù):
第一個參數(shù)可以是HTML標(biāo)簽名,組件或者函數(shù)都可以;此參數(shù)是必須的;
第二個為數(shù)據(jù)對象,虛擬dom的配置(可選);
第三個為子節(jié)點(diǎn),支持字符串與數(shù)組(多層嵌套h())(可選)。
vue2.0里面的寫法
render: h => h(App)
等價于?
render:function(h,context){return h(App);}也等價于
render:function(createElement,context){return createElement(App)}假設(shè)我們要生成一些帶錨點(diǎn)的標(biāo)題:子組件想要根據(jù)父組件傳遞的?level?值(1-6)來決定渲染標(biāo)簽?h 幾。
<h1><a name="hello-world" href="#hello-world">Hello world!</a> </h1> <anchored-heading :level="1">Hello world!</anchored-heading>當(dāng)開始寫一個只能通過?level?prop 動態(tài)生成標(biāo)題 (heading) 的組件時,你可能很快想到這樣實現(xiàn):
<script type="text/x-template" id="anchored-heading-template"><h1 v-if="level === 1"><slot></slot></h1><h2 v-else-if="level === 2"><slot></slot></h2><h3 v-else-if="level === 3"><slot></slot></h3><h4 v-else-if="level === 4"><slot></slot></h4><h5 v-else-if="level === 5"><slot></slot></h5><h6 v-else-if="level === 6"><slot></slot></h6> </script>?對于上面的 HTML,這樣定義組件接口實現(xiàn):
Vue.component('anchored-heading', {template: '#anchored-heading-template',props: {level: {type: Number,required: true}} })這里用模板并不是最好的選擇:不但代碼冗長,而且在每一個級別的標(biāo)題中重復(fù)書寫了?<slot></slot>,在要插入錨點(diǎn)元素時還要再次重復(fù)。
雖然模板在大多數(shù)組件中都非常好用,但是顯然在這里它就不合適了。那么,我們來嘗試使用?render?函數(shù)重寫上面的例子:
Vue.component('anchored-heading', {render: function (createElement) {return createElement('h' + this.level, // 標(biāo)簽名稱this.$slots.default // 子節(jié)點(diǎn)數(shù)組)},props: {level: {type: Number,required: true}} })在這個例子中,你需要知道,向組件中傳遞不帶?v-slot?指令的子節(jié)點(diǎn)時,比如?anchored-heading?中的?Hello world!,這些子節(jié)點(diǎn)被存儲在組件實例中的?$slots.default?
你可以通過?this.$slots?訪問靜態(tài)插槽的內(nèi)容,每個插槽都是一個 VNode 數(shù)組
render: function (createElement) {// `<div><slot></slot></div>`return createElement('div', this.$slots.default) }也可以通過?this.$scopedSlots?訪問作用域插槽,每個作用域插槽都是一個返回若干 VNode 的函數(shù)
props: ['message'], render: function (createElement) {// `<div><slot :text="message"></slot></div>`return createElement('div', [this.$scopedSlots.default({text: this.message})]) }ps:
render函數(shù)return什么該組件就渲染什么
以render函數(shù)渲染時,內(nèi)部最好不要出現(xiàn)注釋
?總結(jié):
1.?render方法的實質(zhì)就是生成template模板;?
2.?通過調(diào)用一個方法來生成,而這個方法是通過render方法的參數(shù)傳遞給它的;?
3.?這個方法有三個參數(shù),分別提供標(biāo)簽名,標(biāo)簽相關(guān)屬性,標(biāo)簽內(nèi)部的html內(nèi)容?
4.?通過這三個參數(shù),可以生成一個完整的木模板
備注:
注意:?
render函數(shù)是有限制的,Vue.js 2.X支持,但是1.X無法使用。
總結(jié)
以上是生活随笔為你收集整理的Render函数渲染页面的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Mybatis-9.28
- 下一篇: 2021年质量员-设备方向-通用基础(质