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