我正在尝试为我的应用程序构建动态布局。我有两种不同的布局,一种是DefaultLayout.vue:
<template>
<div>
<main>
<slot/>
</main>
</div>
</template>
Run Code Online (Sandbox Code Playgroud)
第二个是LayoutWithFooter.vue,有两个插槽:
<template>
<div>
<main>
<slot/>
</main>
<footer>
<slot name="footer"/>
</footer>
</div>
</template>
Run Code Online (Sandbox Code Playgroud)
我处理动态布局的无渲染组件如下所示:
<script>
import Vue from 'vue';
import DefaultLayout from './DefaultLayout';
import LayoutWithFooter from './LayoutWithFooter';
export default {
props: {
name: {
type: String,
required: true
}
},
created(){
this.registerComponent("DefaultLayout", DefaultLayout);
this.registerComponent("LayoutWithFooter", LayoutWithFooter);
this.$parent.$emit('update:layout', this.name);
},
methods: {
registerComponent(name, component) {
if(!Vue.options.components[name]) {
Vue.component(name, component);
}
}
},
render() {
return this.$slots.default[0];
},
}
</script>
Run Code Online (Sandbox Code Playgroud)
所有这些都适用于 ,DefaultLayout.vue但是当我想使用 时LayoutWithFooter.vue,它无法处理其中的两个插槽。这是一个示例用法:
<script>
import Vue from 'vue';
import DefaultLayout from './DefaultLayout';
import LayoutWithFooter from './LayoutWithFooter';
export default {
props: {
name: {
type: String,
required: true
}
},
created(){
this.registerComponent("DefaultLayout", DefaultLayout);
this.registerComponent("LayoutWithFooter", LayoutWithFooter);
this.$parent.$emit('update:layout', this.name);
},
methods: {
registerComponent(name, component) {
if(!Vue.options.components[name]) {
Vue.component(name, component);
}
}
},
render() {
return this.$slots.default[0];
},
}
</script>
Run Code Online (Sandbox Code Playgroud)
现在的问题是,“页脚插槽的内容”不会在LayoutWithFooter.vue.
小智 1
首先,我希望您注意在示例中定义插槽级别。您提供了此代码:
<template>
<layout name="LayoutWithFooter">
<div>
<div>some content</div>
<div slot="footer">content for the footer slot</div>
</div>
</layout>
</template>
Run Code Online (Sandbox Code Playgroud)
但实际上你div slot="footer"并不是指组件footer的插槽LayoutWithFooter.vue。这是因为无论如何第一个孩子指的是default插槽。结果看起来像:
“您想要为default插槽设置内容,并且在该default插槽内您尝试为footer插槽设置内容” - 但这是两个不同的范围。
正确的选项如下所示:
<template>
<layout name="LayoutWithFooter">
<!-- default slot content -->
<div>
<div>some content</div>
</div>
<!-- footer slot content -->
<div slot="footer">content for the footer slot</div>
</layout>
</template>
Run Code Online (Sandbox Code Playgroud)
我根据您提供的代码和结构准备了一些示例。在那里,您可以切换布局并检查其工作原理,并在一种布局中使用不同的组件插槽。
在这里检查: https: //codesandbox.io/s/sad-fog-zr39m
PS也许有些观点并不完全清楚,请回复我的答案,我会尽力解释更多和/或为您提供更多链接和来源。