vue 组件 slot进阶---弹窗插槽

有时我们需要多个插槽。例如对于一个带有如下模板的组件:

<div class="modal" v-if="visible">
  <div class="modal-content">
    <header>
      <!-- 我们希望把页头放这里 -->
    </header>
    <main>
      <!-- 我们希望把主要内容放这里 -->
    </main>
    <footer>
      <!-- 我们希望把页脚放这里 -->
    </footer>
  </div>
</div>

对于这样的情况,slot元素有一个特殊的属性:name。这个属性可以用来定义额外的插槽:

<div class="modal" v-if="visible">
  <div class="modal-content">
    <header>
      <slot name="header"></slot>
    </header>
    <main>
      <slot></slot>
    </main>
    <footer>
      <slot name="footer"></slot>
    </footer>
  </div>
</div>

没有写 name 属性的情况下,其实它会自动带隐含的名字“default”,也就是所说的“匿名插槽”。

带有 name 属性的插槽,我们称为“具名插槽”。

在向具名插槽提供内容的时候,我们可以在一个 template 元素上使用 v-slot 指令,并以 v-slot 的参数的形式提供其名称:

<Modal :visible.sync="visible">
  <template v-slot:header>
    <h1>Modal title</h1>
  </template>

  <div>main content</div>
  <div>main content</div>

  <template v-slot:footer>
    <p>Modal footer</p>
  </template>
</Modal>

弹窗组件:
父App.vue

<template>
  <div id="app">
    <button @click="visible = true" class="btn">打开“协议”弹框</button>
    <button @click="visibleApply = true" class="btn">打开“成为大牛”弹框</button>

    <!-- “协议”弹框 -->
    <Modal
      customClassName="agreement-modal"
      title="用户协议"
      :visible.sync="visible"
      @confirm="confirm"
    >
      <template>
        <div class="hignlight">欢迎来到XXX</div>
        <div class="content">
          请您仔细阅读以下条款,如果您对本使用须知的任何条款表示异议,您可以选择不进入,此用户协议范围包含产品。用户注册成功后,将给每个用户一个用户帐号,该用户帐号由用户负责保管;用户应
       
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Vue组件中调用弹窗组件可以通过以下步骤实现: 1. 首先,创建一个弹窗组件,可以在组件的`template`中定义弹窗的内容和样式。 ```vue <template> <div class="modal"> <div class="modal-content"> <!-- 弹窗内容 --> <slot></slot> </div> </div> </template> <script> export default { name: 'Modal', // ...组件的其他配置 } </script> <style> .modal { /* 弹窗样式 */ } .modal-content { /* 弹窗内容样式 */ } </style> ``` 2. 在需要使用弹窗的父组件中,引入并注册弹窗组件。 ```vue <template> <div> <!-- 点击按钮触发弹窗 --> <button @click="openModal">打开弹窗</button> <!-- 使用弹窗组件 --> <Modal v-if="showModal"> <!-- 弹窗内容 --> <h2>这是一个弹窗</h2> <p>欢迎使用弹窗组件!</p> <button @click="closeModal">关闭</button> </Modal> </div> </template> <script> import Modal from './Modal.vue'; export default { name: 'ParentComponent', components: { Modal, }, data() { return { showModal: false, }; }, methods: { openModal() { this.showModal = true; }, closeModal() { this.showModal = false; }, }, } </script> ``` 在上述代码中,点击按钮 `打开弹窗` 会触发 `openModal` 方法,将 `showModal` 属性设置为 `true`,从而显示弹窗组件弹窗组件在父组件中使用时,可以通过插槽slot)传递弹窗的内容和样式。 这样,当点击按钮时,弹窗组件会显示,并且可以通过弹窗中的按钮或其他交互元素来关闭弹窗

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值