Vue插槽slot的使用


Vue 2 官方文档:https://cn.vuejs.org/v2/guide/components-slots.html

Vue 2 示例

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <meta http-equiv="X-UA-Compatible" content="ie=edge" />
        <title>Document</title>
    </head>
    <body>
        <div id="app">
            <one>
                <h1 slot="header">333333</h1>
            </one>
        </div>
    </body>
</html>
<template id="one">
    <div>
        <slot name="header">默认内容2222</slot>
    </div>
</template>
<script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.14/vue.js"></script>
<script>
    Vue.component("one", {
        template: "#one",
    });
    var vue = new Vue({
        el: "#app",
    });
</script>

Vue 3 插槽

Vue 3 官方文档:https://cn.vuejs.org/guide/components/slots.html

具名插槽

父组件

<template>
    <div class="about">
        <h1>This is an about page</h1>
        <hr />
        <aboutCom ref="aboutCom">
            <template v-slot:header>
                <h1>插槽内容</h1>
            </template>
        </aboutCom>
    </div>
</template>
<script>
    import aboutCom from "../components/aboutCom.vue";
    import aboutComChild from "../components/aboutComChild.vue";
    export default {
        components: {
            aboutCom,
            aboutComChild,
        },
    };
</script>

子组件

<template>
    <div>
        <h2>这是about的子组件</h2>
        <slot name="header">默认内容222222222</slot>
        <hr />
        <aboutComChild ref="aboutComChild"></aboutComChild>
    </div>
</template>

作用域插槽

子组件

<template>
    <div>
        <slot name="header" :user="userData">{{ userData.name }}</slot>
    </div>
</template>
<script>
    import aboutComChild from "./aboutComChild.vue";
    export default {
        components: {
            aboutComChild,
        },
        data() {
            return {
                userData: { name: "张三", age: 25 },
            };
        },
    };
</script>

父组件

<aboutCom>
    <template v-slot:header="slotProps">
        <h1>{{ slotProps.user.name }} - {{ slotProps.user.age }}</h1>
    </template>
</aboutCom>

简化写法

Vue 3.2+ 支持在模板中使用简化的作用域插槽语法:

<!-- 简化前 -->
<template v-slot:header="slotProps"></template>
<!-- 简化后 -->
<template #header="slotProps"></template>

默认插槽与版本写法对照

上面都是”具名插槽”,最基础的其实是默认插槽(不写名字,直接使用 <slot>):

<!-- 子组件 -->
<template>
    <div>
        <slot>没传内容时的默认兜底文字</slot>
    </div>
</template>

<!-- 父组件:直接把内容写在组件标签里即可 -->
<my-comp>这里是插入的内容</my-comp>

Vue 2 与 Vue 3 插槽写法对照

场景 Vue 2 写法 Vue 3 写法
默认插槽 直接写在组件标签内 同 Vue 2(<slot> 不变)
具名插槽 <template slot="header"> <template v-slot:header>#header
作用域插槽 <template slot="x" slot-scope="props"> <template v-slot:x="props">#x="props"

一句话记忆:Vue 3 把 slot / slot-scope 统一收进了 v-slot(简写 #),其余概念(默认 / 具名 / 作用域)完全一致。


文章作者: 弈心
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 弈心 !
评论
  目录