VUE的作用域插槽

153 阅读1分钟

作用域插槽

在父组件中可以访问子组件的数据

子组件

<template>
    <h1>
        // 1.把子组件的变量传递给父组件
        <slot :user="user">
            {{user.name}}
        </slot>
    </h1>
</template>


<script>
export default {
    data() {
        return {
            user: {
                name: '周杰伦',
                age: 18
            }
        }
    }
}
</script>

<style scoped lang="scss">
</style>

父组件

<template>
    <div>
        <Child>
            // 2.父组件接收子组件的变量
            <template v-slot="{user}">
                {{user.age}}
            </template>
        </Child>
    </div>
</template>

<script>
export default {
    name: 'Home',
    data() {
        return {
        }
    },
    components: {
        Child: () => import(/* webpackChunkName: "CustomButton" */'@/components/Child'),
    }
}
</script>