惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

D
DataBreaches.Net
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
云风的 BLOG
云风的 BLOG
B
Blog
博客园 - Franky
I
InfoQ
A
About on SuperTechFans
博客园_首页
L
LangChain Blog
量子位
腾讯CDC
Microsoft Security Blog
Microsoft Security Blog
博客园 - 【当耐特】
美团技术团队
V
V2EX
Apple Machine Learning Research
Apple Machine Learning Research
雷峰网
雷峰网
MongoDB | Blog
MongoDB | Blog
Microsoft Azure Blog
Microsoft Azure Blog
月光博客
月光博客
T
The Blog of Author Tim Ferriss
P
Proofpoint News Feed
G
Google Developers Blog
Last Week in AI
Last Week in AI

博客园 - linFen

Ubuntu下使用ProcDump ubuntu 20.04 搭建 ProcDump Anaconda 常用命令 记录codesmith 断点调试弹不了vs Vue模板语法——键盘事件修饰符 Vue模板语法——事件修饰符 Vue模板语法——v-on 事件绑定 Vue模板语法——v-model 双向数据绑定 Vue模板语法——v-once 数据响应式 Vue模板语法——数据绑定指令 Vue模板语法——v-cloak vue响应性原理 ES6其他 css其他 JS其他 前端VUE 前端 Vue 之 Mixins (混入) Vue 响应性
vue 中slot
linFen · 2024-01-28 · via 博客园 - linFen

插槽使用场景

- 该组件被多个地方使用
- 每个父组件中对该组件的内部有一部分需要特殊定制
- slot可以让我们更好的复用组件的同时并对其定制化处理
- 可以理解为父组件想子组件传递了一段 html 文本
要求:
    1.子组件模板包含至少一个 插槽 <slot></slot>
    2.父组件整个内容片段将插入到 slot 所在的 DOM 位置,并替换掉 slot 标签本身

1.普通插槽 slot

父组件: 负责分发插槽内容
        <child ref=child>
            我是父组件分发给 child 的所有内容
        </child>
        父组件获取子组件可以通过 this.$refs.child 来做操作

子组件:  <template>
            <slot>这里可以放一些默认值</slot>
        </template>
        模板中放置一个 <slot></slot>组件,
        我们可以自定义组件中的方法和数据,封装一些通用逻辑,比如前几篇中封装的 scroll滚动组件

2.具名插槽 子组件通过 name 属性 来匹配父组件分发的内容

父组件: 添加 slot 属性来作为标识
        <div slot="header">我是 header 分发的内容 111</div>
        <div slot="main">我是 main 分发的内容222</div>
        <div slot="footer">我是 footer 分发的内容333</div>

      在2.6.0 以上使用的是 v-slot:header; 默认插槽为: v-slot:default

子组件: slot 添加 name 属性来接受父组件分发的 DOM 元素
        <template>
            <slot name="header"></slot>
            <slot name="main"></slot>
            <slot name="footer"></slot>
        </template>
    当然,我们还可以调换插槽的位置

3.作用域插槽 父组件可以接收来自子组件的 slot 传递过来的参数值

可以理解为: 子组件中的作用域插槽可以为父组件中的插槽的展示提供数据

子组件:
    <template>
        <div>
            <slot name="header" :value="value"></slot>
        </div>
    </template>
    <script>
        export default {
            data() {
                return {
                    value: '我是子组件的值'
                }
            }
        }
    </script>

父组件:
    <child>
        <template slot="header" slot-scope="slotHeaderProps">
            渲染子组件传过来的对象中 value值{{ slotHeaderProps.value }}
        </template>
    </child>

    在 2.6 以上绑定值的方式: v-slot:header="slotHeaderProps"
    而且可以使用解构 v-slot:header="{value}", 将子组件传过来的值解构

    还有就是, 我们可以把 slot直接写在子组件行内, 不必另起一个 template
    即这样: <child v-slot:header="{value}">{{value}}</child>