前言
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>
小结
知其然知其所以然,方可以不变应万变。
发表回复