渲染函數(shù) render
通過渲染函數(shù)渲染組件
Vue.component('myComponent', {
render (h) { // createElement
return h(
'div', // HTML tag、自定義組件、異步組件
{ // 屬性對象
attrs: { // 標(biāo)簽屬性
id: 'wrap'
},
class: { // 類名
'my-com': true
},
props: { // DOM 屬性,props
user: 'wdapp'
},
style: { // 樣式
color: 'red',
fontSize: '18px'
},
on: { // 綁定事件
mouseenter: function () {
console.log('click')
}
},
key: 'myKey', // 唯一key值
ref: 'myRef', // 獲取DOM元素的標(biāo)識
},
[// 子節(jié)點
"文本節(jié)點", // 文本節(jié)點
h('h1', "內(nèi)容"), // 虛擬節(jié)點
]
)
}
})
渲染后:
// html
<div id="wrap" class="my-com" style="color: red; font-size: 18px;">文本節(jié)點<h1>內(nèi)容</h1></div>
JSX
通過以上方式創(chuàng)建虛擬DOM,語法比較繁瑣。可以使用JSX(JavaScript XML)語法,配合createElement輕松的創(chuàng)建虛擬DOM。
Vue使用JSX語法,需要配合Babel插件進(jìn)行解析。
import AnchoredHeading from './AnchoredHeading.vue'
new Vue({
el: '#demo',
render: function (h) {
return (
<AnchoredHeading level={1}>
<span>Hello</span> world!
</AnchoredHeading>
)
}
})
函數(shù)式組件
Vue.component('smart-list', {
functional: true, // 函數(shù)式組件
props: { // 屬性
items: {
type: Array,
required: true
}
},
// context 上下文
render: function (createElement, context) {
return createElement(
"button",
context.data, // 把smart-list自定義組件的整個"數(shù)據(jù)對象"傳遞給button
context.children // 把smart-list自定義組件的所有子節(jié)點傳遞給button
)
}
})
"數(shù)據(jù)對象": 指的是上文提到的createElement的第二個參數(shù),之類包括 props、class、id等
使用組件:
<smart-list id="Smart" class="smart-list" @click="handelClick">Smart Btn</smart-list>
渲染為:
<button id="Smart" class="smart-list">Smart Btn</button>