在某些方面,root的行为不像常规组件:您可以使用can't pass props
,也不能直接在其模板中使用<slot>
s(related:vue/#4485).
看看电流源:$slots
are resolved by和resolveSlots
function,在根组件上调用点resolveSlots
,它的$options._renderChildren
是undefined
,因此没有解决任何插槽.这并不重要,但实际上,根组件从未填充其$options._renderChildren
.
据说<slot>
处理逻辑是complicates things a bit,所以这可能是一个设计决定.
Alternative solution
通常用于处理请求的模式只是将内容包装到另一个组件(比如<app>
)中,然后从那里开始.
Vue.component('app', {
template: `<div>
<h2>I'm the <app> component title</h2>
<slot>app slot default text</slot>
</div>`
});
new Vue({
el: '#app'
});
<script src="https://unpkg.com/vue@2.5.13/dist/vue.js"></script>
<div id="app">
<app>
I'm the contents of app's template and was declared in root
</app>
</div>
在下面的演示中,查看this.$slots
如何不为root填充,即使它有<slot>
个.
Vue.component('app', {
template: `<div>
<h2>I'm the <app> component title</h2>
<slot>app slot default text</slot>
</div>`,
created() {
console.log("<app>'s VDOM children (LENGTH): ", this.$options._renderChildren.length);
console.log("<app>'s slots (LENGTH): ", this.$slots.default.length);
}
});
new Vue({
el: '#app',
created() {
console.log("root's VDOM children: ", this.$options._renderChildren);
console.log("root's slots: ", this.$slots);
}
});
<script src="https://unpkg.com/vue@2.5.13/dist/vue.min.js"></script>
<div id="app">
<app>
I'm the contents of app's template
</app>
<slot>root's slot's default content, won't make it into $slots, check the console</slot>
</div>