undefinedfix
Sign in

How to pass a component to slot as a variable

user620543 edited in Sat, 24 Sep 2022

Write a subcomponent TreeShape.vue , want to pass in component variables outside:

<template>
    <!-- parent传进title和content -->
    <div>
        <div class = "tree-title"
            @click = "onClickTreeTitle">
            {{title}}
        </div>
        <slot v-show = "isExpand">

        </slot>
    </div>
</template>

<script>
export default {
    props:{
        title: {
            type: String,
            default: ""
        }
    },
    data(){
        return {
            isExpand: false
        }
    },
    methods:{
        onClickTreeTitle(){
            this.isExpand = !this.isExpand;
        }
    }
}
</script>

Parent component treebox . Vue is as follows, which contains the sub component treeshape . The number of vues is dynamic, and the components passed to slot are also dynamic, similar to the following:

<template>
    <div>
        <TreeShape
            v-for = "treeShape in treeShapeArray"
            :key = "treeShape.id"
            :title="treeShape.title"
            
        >
        ???
        </TreeShape>
    </div>
</template>

<script>
import testC1 from './testC1'
import testC2 from './testC2'
import TreeShape from './TreeShape'
const treeShapeArray = [{
    id:"1",
    title: "aaaa",
    comp: testC1
},
{
    id:"2",
    title: "bbb",
    comp: testC2
}];
export default {
    data(){
        return {
            treeShapeArray
        }
    },
    components:{
        TreeShape,
        testC1,
        testC2
    }
}
</script>

<style scoped>

</style>

How to realize it?

2 Replies
user3740951
commented on Sat, 24 Sep 2022

There is a component called component. You can learn about it

<TreeShape
        v-for = "treeShape in treeShapeArray"
        :key = "treeShape.id"
        :title="treeShape.title"
        
    >
    <component v-if="!!treeShape.comp" :is="treeShape.comp"></component>
</TreeShape>
Harrison
commented on Sat, 24 Sep 2022

Dynamic components, https://cn.vuejs.org/v2/guide...