前言
vue.js的靈魂是組件,而組件的靈魂是插槽。借助於插槽,我們能最大程度上實現組件復用。本文主要是對插槽的實現機制進行詳細概括總結,在某些場景中,有一定的用處。知其然知其所以然,掌握vue.js實現原理,不僅可以提升自身解決問題的能力,還可以學習到大神們編程思想和開發范式。
樣例代碼
<!-- 子組件comA -->
<template>
<div class='demo'>
<slot><slot>
<slot name='test'></slot>
<slot name='scopedSlots' test='demo'></slot>
</div>
</template>
<!-- 父組件 -->
<comA>
<span>這是默認插槽</span>
<template slot='test'>這是具名插槽</template>
<template slot='scopedSlots' slot-scope='scope'>這是作用域插槽(老版){{scope.test}}</template>
<template v-slot:scopedSlots='scopeProps' slot-scope='scope'>這是作用域插槽(新版){{scopeProps.test}}</template>
</comA>
透過現象看本質
插槽的作用是實現內容分發,實現內容分發,需要兩個條件:
- 占位符
- 分發內容
組件內部定義的slot標簽,我們可以理解為占位符,父組件中插槽內容,就是要分發的內容。插槽處理本質就是將指定內容放到指定位置。廢話不多說,從本篇文章中,將能了解到:
- 插槽的實現原理
render方法中如何使用插槽
實現原理
vue組件實例化順序為:父組件狀態初始化(data、computed、watch...) --> 模板編譯 --> 生成render方法 --> 實例化渲染watcher --> 調用render方法,生成VNode --> patch VNode,轉換為真實DOM --> 實例化子組件 --> ......重復相同的流程 --> 子組件生成的真實DOM掛載到父組件生成的真實DOM上,掛載到頁面中 --> 移除舊節點
從上述流程中,可以推測出:
- 父組件模板解析在子組件之前,所以父組件首先會獲取到插槽模板內容
- 子組件模板解析在后,所以在子組件調用
render方法生成VNode時,可以借助部分手段,拿到插槽的VNode節點 - 作用域插槽可以獲取子組件內變量,因此作用域插槽的
VNode生成,是動態的,即需要實時傳入子組件的作用域scope
整個插槽的處理階段大致分為三步:
- 編譯
- 生成渲染模板
- 生成VNode
以下面代碼為例,簡要概述插槽運轉的過程。
<div id='app'>
<test>
<template slot="hello">
123
</template>
</test>
</div>
<script>
new Vue({
el: '#app',
components: {
test: {
template: '<h1>' +
'<slot name="hello"></slot>' +
'</h1>'
}
}
})
</script>
父組件編譯階段
編譯是將模板文件解析成AST語法樹,會將插槽template解析成如下數據結構:
{
tag: 'test',
scopedSlots: { // 作用域插槽
// slotName: ASTNode,
// ...
}
children: [
{
tag: 'template',
// ...
parent: parentASTNode,
children: [ childASTNode ], // 插槽內容子節點,即文本節點123
slotScope: undefined, // 作用域插槽綁定值
slotTarget: "\"hello\"", // 具名插槽名稱
slotTargetDynamic: false // 是否是動態綁定插槽
// ...
}
]
}
父組件生成渲染方法
根據AST語法樹,解析生成渲染方法字符串,最終父組件生成的結果如下所示,這個結構和我們直接寫render方法一致,本質都是生成VNode, 只不過_c或h是this.$createElement的縮寫。
with(this){
return _c('div',{attrs:{"id":"app"}},
[_c('test',
[
_c('template',{slot:"hello"},[_v("\n 123\n ")])],2)
],
1)
}
父組件生成VNode
調用render方法,生成VNode,VNode具體格式如下:
{
tag: 'div',
parent: undefined,
data: { // 存儲VNode配置項
attrs: { id: '#app' }
},
context: componentContext, // 組件作用域
elm: undefined, // 真實DOM元素
children: [
{
tag: 'vue-component-1-test',
children: undefined, // 組件為頁面最小組成單元,插槽內容放放到子組件中解析
parent: undefined,
componentOptions: { // 組件配置項
Ctor: VueComponentCtor, // 組件構造方法
data: {
hook: {
init: fn, // 實例化組件調用方法
insert: fn,
prepatch: fn,
destroy: fn
},
scopedSlots: { // 作用域插槽配置項,用於生成作用域插槽VNode
slotName: slotFn
}
},
children: [ // 組件插槽節點
tag: 'template',
propsData: undefined, // props參數
listeners: undefined,
data: {
slot: 'hello'
},
children: [ VNode ],
parent: undefined,
context: componentContext // 父組件作用域
// ...
]
}
}
],
// ...
}
在vue中,組件是頁面結構的基本單元,從上述的VNode中,我們也可以看出,VNode頁面層級結構結束於test組件,test組件children處理會在子組件初始化過程中處理。子組件構造方法組裝與屬性合並在vue-dev\src\core\vdom\create-component.js createComponent方法中,組件實例化調用入口是在vue-dev\src\core\vdom\patch.js createComponent方法中。
子組件狀態初始化
實例化子組件時,會在initRender -> resolveSlots方法中,將子組件插槽節點掛載到組件作用域vm中,掛載形式為vm.$slots = {slotName: [VNode]}形式。
子組件編譯階段
子組件在編譯階段,會將slot節點,編譯成以下AST結構:
{
tag: 'h1',
parent: undefined,
children: [
{
tag: 'slot',
slotName: "\"hello\"",
// ...
}
],
// ...
}
子組件生成渲染方法
生成的渲染方法如下,其中_t為renderSlot方法的簡寫,從renderSlot方法,我們就可以直觀的將插槽內容與插槽點聯系在一起。
// 渲染方法
with(this){
return _c('h1',[ _t("hello") ], 2)
}
// 源碼路徑:vue-dev\src\core\instance\render-helpers\render-slot.js
export function renderSlot (
name: string,
fallback: ?Array<VNode>,
props: ?Object,
bindObject: ?Object
): ?Array<VNode> {
const scopedSlotFn = this.$scopedSlots[name]
let nodes
if (scopedSlotFn) { // scoped slot
props = props || {}
if (bindObject) {
if (process.env.NODE_ENV !== 'production' && !isObject(bindObject)) {
warn(
'slot v-bind without argument expects an Object',
this
)
}
props = extend(extend({}, bindObject), props)
}
// 作用域插槽,獲取插槽VNode
nodes = scopedSlotFn(props) || fallback
} else {
// 獲取插槽普通插槽VNode
nodes = this.$slots[name] || fallback
}
const target = props && props.slot
if (target) {
return this.$createElement('template', { slot: target }, nodes)
} else {
return nodes
}
}
作用域插槽與具名插槽區別
<!-- demo -->
<div id='app'>
<test>
<template slot="hello" slot-scope='scope'>
{{scope.hello}}
</template>
</test>
</div>
<script>
var vm = new Vue({
el: '#app',
components: {
test: {
data () {
return {
hello: '123'
}
},
template: '<h1>' +
'<slot name="hello" :hello="hello"></slot>' +
'</h1>'
}
}
})
</script>
作用域插槽與普通插槽相比,主要區別在於插槽內容可以獲取到子組件作用域變量。由於需要注入子組件變量,相比於具名插槽,作用域插槽有以下幾點不同:
- 作用域插槽在組裝渲染方法時,生成的是一個包含注入作用域的方法,相對於
createElement生成VNode,多了一層注入作用域方法包裹,這也就決定插槽VNode作用域插槽是在子組件生成VNode時生成,而具名插槽是在父組件創建VNode時生成。_u為resolveScopedSlots,其作用為將節點配置項轉換為{scopedSlots: {slotName: fn}}形式。
with (this) {
return _c('div', {
attrs: {
"id": "app"
}
}, [_c('test', {
scopedSlots: _u([{
key: "hello",
fn: function(scope) {
return [_v("\n " + _s(scope.hello) + "\n ")]
}
}])
})], 1)
}
- 子組件初始化時會處理具名插槽節點,掛載到組件
$slots中,作用域插槽則在renderSlot中直接被調用
除此之外,其他流程大致相同。插槽作用機制不難理解,關鍵還是模板解析與生成render函數這兩步內容較多,流程較長,比較難理解。
使用技巧
通過以上解析,能大概了解插槽處理流程。工作中大部分都是用模板來編寫vue代碼,但是某些時候模板有一定的局限性,需要借助於render方法放大vue的組件抽象能力。那么在render方法中,我們插槽的使用方法如下:
具名插槽
插槽處理一般分為兩塊:
- 父組件
父組件只需要寫成模板編譯成的渲染方法即可,即指定插槽slot名稱
- 子組件
由於子組件時直接拿父組件初始化階段生成的VNode,所以子組件只需要將slot標簽替換為父組件生成的VNode,子組件在初始化狀態時會將具名插槽掛載到組件$slots屬性上。
<div id='app'>
<!-- <test>-->
<!-- <template slot="hello">-->
<!-- 123-->
<!-- </template>-->
<!-- </test>-->
</div>
<script>
new Vue({
// el: '#app',
render (createElement) {
return createElement('test', [
createElement('h3', {
slot: 'hello',
domProps: {
innerText: '123'
}
})
])
},
components: {
test: {
render(createElement) {
return createElement('h1', [ this.$slots.hello ]);
}
// template: '<h1>' +
// '<slot name="hello"></slot>' +
// '</h1>'
}
}
}).$mount('#app')
</script>
作用域插槽
作用域插槽使用比較靈活,可以注入子組件狀態。作用域插槽 + render方法,對於二次組件封裝作用非常大。舉個栗子,在對ElementUI table組件進行基於JSON數據封裝時,作用域插槽用處就非常大了。
<div id='app'>
<!-- <test>-->
<!-- <span slot="hello" slot-scope='scope'>-->
<!-- {{scope.hello}}-->
<!-- </span>-->
<!-- </test>-->
</div>
<script>
new Vue({
// el: '#app',
render (createElement) {
return createElement('test', {
scopedSlots:{
hello: scope => { // 父組件生成渲染方法中,最終轉換的作用域插槽方法和這種寫法一致
return createElement('span', {
domProps: {
innerText: scope.hello
}
})
}
}
})
},
components: {
test: {
data () {
return {
hello: '123'
}
},
render (createElement) {
// 作用域插槽父組件傳遞過來的是function,需要手動調用生成VNode
let slotVnode = this.$scopedSlots.hello({ hello: this.hello })
return createElement('h1', [ slotVnode ])
}
// template: '<h1>' +
// '<slot name="hello" :hello="hello"></slot>' +
// '</h1>'
}
}
}).$mount('#app')
</script>
小結
知其然知其所以然,方可以不變應萬變。
