【Vue3】slot插槽之作用域插槽【基于v-slot传参】

作用域插槽的作用就是:子组件【插槽位置】向【父组件实现位置】传递参数的功能

 

父组件

<template>
    <img alt="Vue logo" src="./assets/logo.png">
    <HelloWorld msg="Welcome to Your Vue.js App">
        <!--这里的data需从子组件的插槽中传入获取-->
        <template v-slot="data">
            <div>父组件插槽接收的子组件的数据为:data={
   
   {data}}</div>
        </template>
    </HelloWorld>
</template>

<script>
    import HelloWorld from "./components/HelloWorld.vue";

    export default {
        name: "App",
        components: {
            HelloWorld,
        },
    };
</script>

<style>
    #app {
        font-family: Avenir, Helvetica, Arial, sans-serif;
        -webkit-font-smoothing: antialiased;
        -moz-osx-font-smoothing: grayscale;
        text-align: center;
        color: #2c3e50;
        margin-top: 60px;
    }
</style>

子组件

<!--
    功能:纯CSS3来创建Switch开关功能【基于checkbox标签的选中和取消,来模拟button功能】
    特殊说明:
        1、隐藏input,然后把label和input通过for-id标签关联!
        2、label是inline标签,为此无法直接设置尺寸,中间嵌入一个div元素被label包裹即可!
-->

<template>
    <div>
        <h1>这里是子组件</h1>
        <!--这里的参数自动传入【父组件】插槽内部-->
        <slot :obj="obj"></slot>
    </div>
</template>

<script>
    import { ref, reactive, toRefs } from "vue";

    export default {
        name: "HelloWorld",
        props: {
            msg: String,
        },
        setup() {

            let _data = reactive({
                obj: {
                    name: "kirin",
                    age: 18,
                },
            });


            return {
                ...toRefs(_data),
            };
        },
    };
</script>


<style scoped lang="scss">


</style>

猜你喜欢

转载自blog.csdn.net/weixin_43343144/article/details/120823432
今日推荐