Vue render函數,官方文檔定義絕大部分時候我們使用template 來創建html 模板,但是純html 和css都基本上都不具有編程能力,而當我們想使用
javascript的編程能力時,我們可以用render 函數來創建html 模板
1.使用簡單的tamplate 去創建html 模板
// 使用簡單的template 去創建html 模板 new Vue({ el:'#test', data:{ msg:'czczczcz' }, template: '<h1> {{this.msg}} </h1>' // 我們使用template 去創建html 模板 })
2.當我們現在需求比較復雜,根據傳入的一組標簽組去創建模板,讓我們先看看使用tamplate的方法
<div id="test">
<div v-html="jstem()">
</div>
</div>
<script type="text/javascript">
new Vue({
el:'#test',
data:{
msg:['h1','h3','span','ul'] //簡單的一組標簽組
},
// 如果是直接使用標簽我實在沒想到辦法 。我能想到的只能是
methods: {
jstem () {
let html = '';
if(this.msg) {
this.msg.forEach(item => {
html += `<${item}>${item}</${item}>`
})
}
return html
}
}
})
</script>
上面的話還是使用javascript的編程你能力,我總結的是,就是當組件的html 模板都不固定,可能都需要一定的業務邏輯才能確定時,我們就可以考慮去使用render 函數,創建html模板,官方文檔還講明,template 最終還是要通過模板解析的,一系列底層操作后生成虛擬dom,而rander函數比tamplate更接近編輯器,也就是更容易轉話成虛擬dom。
render 函數
render 函數傳入一個createElement 方法,而這個方法,我們一般簡寫為h ,可以參閱vue-cli main.js 的 render: h => h(App)
<div id="test">
</div>
<script type="text/javascript">
new Vue({
el:'#test',
data:{
msg:['h1','h3','span','ul'] //簡單的一組標簽組
},
render: function(h) {
return h(
'div', //傳入的為一個節點的名稱
{},
this.msg.map(function(item){ //第二個傳入的為節點的值,值可以時一組元素節點
return h(item,item)
})
)
}
})
render 函數內傳入的第二個參數 data ,一系列屬性,包括 class,style,arrts,props,domprops,on,nativeOn,directives,scopedSlots,slot,key,ref,refInfor
具體的用法請詳見官方文檔
vue 插槽,主要是用於組件標簽內信息,在組件內部展示,最新的slot 和slot-scope已經被官方放棄,且不會出現Vue3中,vue 新引入了v-slot 指令
官方文檔上的列子
//定義一個baseLayout 組件
<div class="container">
<header>
<slot name="header"></slot>
</header>
<main>
<slot></slot>
</main>
<footer>
<slot name="footer"></slot>
</footer>
</div>
// 上面定義了一個子組件, 子組件有三個插槽,header,footer,還有一個匿名插槽,其實是default
// 父組件內容 使用了v-slot
<base-layout>
<template v-slot:header>
<h1>Here might be a page title</h1>
</template>
<p>A paragraph for the main content.</p>
<p>And another one.</p>
<template v-slot:footer>
<p>Here's some contact info</p>
</template>
</base-layout>
// 如果不使用v-slot 舊特性,定義具名
<base-layout>
<h1 slot='header'>Here might be a page title</h1>
<p>A paragraph for the main content.</p>
<p>And another one.</p>
<p slot='footer'>Here's some contact info</p>
</slot >
最終會渲染出
<div class="container">
<header>
<h1>Here might be a page title</h1>
</header>
<main>
<p>A paragraph for the main content.</p>
<p>And another one.</p>
</main>
<footer>
<p>Here's some contact info</p>
</footer>
</div>
具名插槽v-slot 的縮寫為#
v-slot='header' 可以寫成 #header
