使用 Vue slot 在基础组件中渲染组件
Using Vue slot to render component within base component
我正在尝试创建一个可重复使用的基本模态组件并利用槽来提供模态内容...它创建了应用程序和模态。在按钮上单击模态显示,但没有内容。如何让我的内容显示在内容指定的插槽中?我是否错误地使用了插槽?
这里有一个 fiddle 来帮助说明我的问题:https://jsfiddle.net/70yyx8z2/19/
// register base modal component
Vue.component('modal', {
template: '#modal-template'
})
// register content component for modal
Vue.component('modal-content', {
template: '#modal-content'
})
// start app
new Vue({
el: '#app',
data: {
showModal: false
}
})
<modal v-if="showModal" @close="showModal = false">
<h3 slot="header">Header here</h3>
<!--
How can I use slot to render the modal content component?
-->
<modal-content></modal-content>
</modal>
从技术上讲,您需要做的就是这个。
<modal-content slot="body"></modal-content>
您可能想从 modal-content
组件中删除 modal-container
。
这是您的 fiddle 更新。
JsFiddle 工作示例
您不能在组件内指定插槽名称,因为在替换插槽之前不会安装它。相反,您可以将组件分配给插槽
<!-- modal content component -->
<script type="text/x-template" id="modal-content">
<form>
<h2>This should show...</h2>
<input type="text" placeholder="user name" />
</form>
</script>
<!-- app -->
<div id="app">
<button id="show-modal" @click="showModal = true">Show Modal</button>
<!-- use the modal component, pass in the prop -->
<modal v-if="showModal" @close="showModal = false">
<h3 slot="header">Header here</h3>
<!--
How can I use slot to render the modal content component?
-->
<modal-content slot="body"></modal-content>
</modal>
</div>
编辑:修复了@thanksd
注意到的一些与命名相关的问题
我正在尝试创建一个可重复使用的基本模态组件并利用槽来提供模态内容...它创建了应用程序和模态。在按钮上单击模态显示,但没有内容。如何让我的内容显示在内容指定的插槽中?我是否错误地使用了插槽?
这里有一个 fiddle 来帮助说明我的问题:https://jsfiddle.net/70yyx8z2/19/
// register base modal component
Vue.component('modal', {
template: '#modal-template'
})
// register content component for modal
Vue.component('modal-content', {
template: '#modal-content'
})
// start app
new Vue({
el: '#app',
data: {
showModal: false
}
})
<modal v-if="showModal" @close="showModal = false">
<h3 slot="header">Header here</h3>
<!--
How can I use slot to render the modal content component?
-->
<modal-content></modal-content>
</modal>
从技术上讲,您需要做的就是这个。
<modal-content slot="body"></modal-content>
您可能想从 modal-content
组件中删除 modal-container
。
这是您的 fiddle 更新。
JsFiddle 工作示例
您不能在组件内指定插槽名称,因为在替换插槽之前不会安装它。相反,您可以将组件分配给插槽
<!-- modal content component -->
<script type="text/x-template" id="modal-content">
<form>
<h2>This should show...</h2>
<input type="text" placeholder="user name" />
</form>
</script>
<!-- app -->
<div id="app">
<button id="show-modal" @click="showModal = true">Show Modal</button>
<!-- use the modal component, pass in the prop -->
<modal v-if="showModal" @close="showModal = false">
<h3 slot="header">Header here</h3>
<!--
How can I use slot to render the modal content component?
-->
<modal-content slot="body"></modal-content>
</modal>
</div>
编辑:修复了@thanksd
注意到的一些与命名相关的问题