Vue 推薦在絕大多數(shù)情況下使用 template 來創(chuàng)建你的 HTML。然而在一些場景中,你真的需要 JavaScript 的完全編程的能力,這就是 render 函數(shù),它比 template 更接近編譯器。vue提供了render函數(shù)大大的提高了JavaScript的編程能力,雖然在日常的使用中是比較少見的但是理解render函數(shù)對應(yīng)加深對Vue組件的使用都是很有幫助的。下面我們就針對render函數(shù)進(jìn)行探討。
render函數(shù)提供一個createElement,而createElement可接受三個參數(shù)具體情況如下:
第一個參數(shù)
第一個參數(shù)可以是HTML標(biāo)簽名,組件或者函數(shù)都可以。
{
type: String || Object || Function,
required: true
}
??
<template>
<div class="dome">
<div id="app">
</div>
</div>
</template>
<script>
Vue.components('dom', {
render: function (createElement) {
return createElement('div');
}
});
new Vue({
el: '#app'
});</script>
第二個參數(shù)
第二個參數(shù)為創(chuàng)建元素的一些屬性。
{
type: Object,
required: false
}
??
Vue.components('dom', {
render: function (createElement) {
return createElement('div', {
'class': {
container: true
},
style: {
cursor: 'pointer'
},
domProps: {
innHTML: 'baz'
}
});
}
});
new Vue({
el: '#app'
});
第三個參數(shù)
第三個參數(shù)為創(chuàng)建元素的子節(jié)點(diǎn)。
{
type: String || Array,
required: false
}
??
<script>
Vue.components('dom', {
render: function (createElement) {
return createElement('div', [
createElement('h1', '主標(biāo)'),
createElement('h2', '副標(biāo)')
]);
}
});
new Vue({
el: '#app'
});
</script>
上述就是render幾個參數(shù)的具體信息,而用render函數(shù)生成的組件的子元素就在$slots.default中。
Vue提供的實(shí)例方法在render函數(shù)中使用
<template>
<div class="dome">
<div id="app">
<dom-input
:value="pValue"
@input="val=>pValue=val">
</dom-input>
</div>
</div>
</template>
<script>
Vue.components('dom-input', {
render: function (createElement) {
const _this = this;
return createElement('div', {
domPopps: {
value: _this.name
},
on: {
input: function () {
_this.$emit('input', event.taget.value);
}
}
});
},
props: {
value: String
}
});
new Vue({
el: '#app',
data: {
pValue: ''
}
});
</script>
上面的例子中我們創(chuàng)建了一個input組件,在組件中當(dāng)輸入的觸發(fā)了input事件emit了input的value;而在外層中接受了這個value讓pValue的值等于value。而pValue又通過props把值傳入input組件中從而實(shí)現(xiàn)了類似v-model的數(shù)據(jù)綁定。
通過了上面render函數(shù)的一個例子我們看到了props和事件的觸發(fā)的使用。