render函數比template模板更加接近編輯器。使用虛擬dom渲染節點能夠提高性能,經過createElement(h)來建立dom節點。template也是被解析成虛擬dom。(虛擬dom實際是一個JavaScript對象)javascript
computed屬性實在vnode虛擬節點created()生命週期執行完後,lazy的模式調用,就是何時須要這個計算屬性,何時去調用computed,而render則是一個主動渲染的過程,首次執行是在beforeMount和mounted兩個生命週期之間。html
下面說一說最重要的createElement函數:java
第一個參數:HTML標籤名,組件或者函數均可以(必須)類型:String/Object/Functionnode
第二個參數:數據對象(可選)類型:Object express
ex:dom
{ // 和`v-bind:class`同樣的 API 'class': { foo: true, bar: false }, // 和`v-bind:style`同樣的 API style: { color: 'red', fontSize: '14px' }, // 正常的 HTML 特性 attrs: { id: 'foo' }, // 組件 props props: { myProp: 'bar' }, // DOM 屬性 domProps: { innerHTML: 'baz' }, // 事件監聽器基於 `on` // 因此再也不支持如 `v-on:keyup.enter` 修飾器 // 須要手動匹配 keyCode。 on: { click: this.clickHandler }, // 僅對於組件,用於監聽原生事件,而不是組件內部使用 // `vm.$emit` 觸發的事件。 nativeOn: { click: this.nativeClickHandler }, // 自定義指令。注意,你沒法對 `binding` 中的 `oldValue` // 賦值,由於 Vue 已經自動爲你進行了同步。 directives: [ { name: 'my-custom-directive', value: '2', expression: '1 + 1', arg: 'foo', modifiers: { bar: true } } ], // Scoped slots in the form of // { name: props => VNode | Array<VNode> } scopedSlots: { default: props => createElement('span', props.text) }, // 若是組件是其餘組件的子組件,需爲插槽指定名稱 slot: 'name-of-slot', // 其餘特殊頂層屬性 key: 'myKey', ref: 'myRef' }
第三個參數:子節點(可選)類型:String/Array編輯器
看例子:函數
export default{ render(h){ const menu_items = ['首頁','搜索','分類','系統']; return h('ul',{ { class:'class-name' }, menu_items.map(item = > h('li',item)) }) } }
至關於性能
<template> <ul> <li v-for="item in menu_items"> {{ item }} </li> </ul> </template>
實際例子使用this
export default { props: { type: { type: String, default: 'normal' }, text: { type: String, default: 'normal' } }, computed: { tag() { switch (this.type) { case 'success': return 1; case 'danger': return 2; case 'warning': return 3; default: return 1; } } }, /** render() { return ( <div class={{ btn: true, 'btn-success': this.type === 'success', 'btn-danger': this.type === 'danger', 'btn-warning': this.type === 'warning' }} onClick={this.handleClick}> {this.text} </div> ); },**/ render(h) { return h('div', { class: { btn: true, 'btn-success': this.type === 'success', 'btn-danger': this.type === 'danger', 'btn-warning': this.type === 'warning' }, domProps: { innerText: this.text }, on: { click: this.handleClick } }); }, methods: { handleClick() { console.log('-----------------------'); console.log('do something'); } } }; <Button type="danger" text="test"></Button>