【问题标题】:Using Vue slot to render component within base component使用 Vue slot 在基础组件中渲染组件
【发布时间】:2017-10-15 18:32:00
【问题描述】:

我正在尝试创建一个可重用的基本模态组件并利用插槽来提供模态内容......它创建了应用程序和模态。在按钮上单击模式显示,但没有内容。如何让我的内容在指定的内容槽内显示?我是不是用错了插槽?

这里有一个小提琴来帮助说明我的问题: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>

【问题讨论】:

    标签: javascript vue.js vuejs2 vue-component


    【解决方案1】:

    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 注意到的一些命名相关问题

    【讨论】:

    • 您可以为组件定义一个槽,但不能为组件范围之外的槽指定一个槽名。跨度>
    • 你说得对,我就是这个意思,写了完全不同的东西。
    • 从技术上讲,您删除了他在 modal-content 插槽中指定自定义内容的能力,但他接受了它,所以...jsfiddle.net/70yyx8z2/24
    【解决方案2】:

    从技术上讲,您需要做的就是这个。

    <modal-content slot="body"></modal-content>
    

    您可能希望从modal-content 组件中删除modal-container

    您的fiddle 已更新。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-03-07
      • 2021-09-11
      • 1970-01-01
      • 2017-12-04
      • 2020-03-25
      • 2019-04-19
      • 2017-11-09
      • 1970-01-01
      相关资源
      最近更新 更多