Vue 3.0 中的slot及使用场景

1. 基本概念

在 Vue 中, slot 用于定义组件中的插槽位置,外部的内容会被插入到组件内部的这个位置。插槽的内容是动态的,可以根据需要进行传递和渲染。它允许开发者在组件外部传递任意内容,并在组件内部进行渲染,主要功能是提高组件的复用性和灵活性。

2. 使用方式

2.1. 默认插槽

最基本的插槽用法是默认插槽,在组件模板中定义 slot,在组件使用时传递内容。

  1. 子组件 MyComponent.vue
html 复制代码
<template>
    <div>
        <slot></slot>
    </div>
</template>
  1. 父组件
html 复制代码
<template>
    </Component>
    <p>This is some content passed to the slot.</p>
    </MyComponent>
</template>

<script>
import MyComponent from './MyComponent.vue';

export default {
    components: {
        MyComponent
    }
};
</script>

2.2. 具名插槽

有时需要在一个组件中使用多个插槽,这时可以使用命名插槽。

  1. 子组件 MyComponent.vue
html 复制代码
<template>
    <div>
        <header>
            <slot name="header"></slot>
        </header>
        <main>
            <slot></slot> <!-- 默认插槽 -->
        </main>
        <footer>
            <slot name="footer"></slot>
        </footer>
    </div>
</template>
  1. 父组件
html 复制代码
<template>
    <MyComponent>
        <template v-slot:header>
            <h1>Header Content</h1>
        </template>
        <template v-slot:footer>
            <p>Footer Content</p>
        </template>
        <p>Main Content</p>
    </MyComponent>
</template>

<script>
import MyComponent from './MyComponent.vue';

export default {
    components: {
        MyComponent
    }
};
</script>

2.3. 作用域插槽

作用域插槽允许子组件将数据传递给插槽内容的父组件,这在需要在插槽内容中使用子组件数据时非常有用。

  1. 子组件 MyComponent.vue
html 复制代码
<template>
    <div>
        <slot :user="user"></slot>
    </div>
</template>

<script>
export default {
    data() {
        return {
            user: {
                name: 'John Doe',
                age: 30
            }
        };
    }
};
</script>
  1. 父组件
javascript 复制代码
<template>
    <MyComponent>
        <template v-slot:default="slotProps">
            <p>User Name: {{ slotProps.user.name }}</p>
            <p>User Age: {{ slotProps.user.age }}</p>
        </template>
    </MyComponent>
</template>

<script>
import MyComponent from './MyComponent.vue';

export default {
    components: {
        MyComponent
    }
};
</script>

3. 使用场景

复用组件结构:插槽允许开发者在不同的上下文中复用相同的组件结构,而改变内容。比如模态框、卡片组件等。

动态内容插入:在一些布局组件中,可以通过插槽动态插入不同的内容,而不需要修改组件本身。

自定义渲染逻辑:在复杂组件中,通过作用域插槽可以将一些数据传递给父组件,从而让父组件来决定如何渲染这些数据。

嵌套组件:在多层嵌套组件中,插槽可以让外层组件将内容传递给内层组件,从而实现复杂的嵌套布局。

相关推荐
aiguangyuan4 天前
ReactNative 快速入门手册
前端开发·reactnative·移动端开发
aiguangyuan6 天前
Taro 开发快速入门手册
taro·前端开发·移动端开发
aiguangyuan8 天前
Taro多端适配技术解析
taro·前端开发·移动端开发
aiguangyuan9 天前
uni-app开发入门手册
uni-app·移动开发·前端开发
hunzhizi12 天前
2024-2025年技术发展趋势深度分析:AI、前端与后端开发的革新之路
微服务·前端开发·后端开发·ai开发·技术趋势·多模态ai
小九今天不码代码14 天前
巧用 CSS linear-gradient 实现多种下划线文字特效(纯 CSS 无需额外标签)
css·css3·前端开发·linear-gradient·前端特效·下划线样式·文字特效
IT技术分享社区17 天前
前端:浏览器Content Security Policy 安全策略介绍和用法
前端·前端开发
小九今天不码代码19 天前
深入理解 CSS 表格布局:table-layout 的秘密与实战详解(附费用报销单案例)
css·前端开发·表格布局·web设计·table-layout·页面优化·样式布局
流年染指悲伤、1 个月前
2024年最新技术趋势分析:AI、前端与后端开发新动向
人工智能·前端开发·后端开发·2024·技术趋势
aiguangyuan1 个月前
微信小程序中的双线程模型及数据传输优化
微信小程序·前端开发