美文网首页
vue 插槽

vue 插槽

作者: 程序猿的小生活 | 来源:发表于2022-07-20 17:05 被阅读0次

1.匿名插槽

例如我想把父组件中内容定位到子组件两个button按钮之间,可以使用插槽
(1)创建子组件cp.vue

<template>
    <div>
        <button>
            开始
        </button>
        <slot ></slot> <!--放一个匿名插槽意思是父组件内容在这里显示 可以放到reny-->
        <button>结束</button>
    </div>
        
</template>

<script>
    export default{
        props:["hello","go"],
        data(){
            return{
                msg:"我是子组件",
                fdf:"欢欢华"
            }
        }
        ,
        methods:{
            
        },
        created() {
            
                 this.$emit('gow',this.msg,this.fdf);
            
        }
        
        
    }
</script>

<style>
</style>

(2)创建父组件

<template>
{{this.$route.query.name}}
{{f}}
<cp hello="父级组件内容" go="你是真六" @gow="jk">
    这里内容会显示在子组件<slot ></slot>放置位置
</cp>
</template>

<script>
    import cp from './cp.vue'
    export default{
        data(){
            return{
                "f":""
            }
        },
        methods:{
            jk(msg,fdf){
                this.f=msg+fdf
            }
        }
        ,
        components:{
            cp
            
        }
        
    }
</script>

<style>
</style>

1.具名插槽

(1)创建子组件

<template>
        <div style="background-color: red;width: 100px;height: 50px;">
            
                <slot name="st"></slot>
        </div>
</template>

<script>
    export default{
        props:["hello","go"],
        data(){
            return{
                msg:"我是儿子",
                fdf:"欢欢华"
            }
        }
        ,
        methods:{
            
        },
        created() {
            
                 this.$emit('gow',this.msg,this.fdf);
            
        }
        
        
    }
</script>

<style>
</style>

(2)创建父组件

<template>
{{this.$route.query.name}}
{{f}}
<cp hello="父级组件内容" go="你是真六" @gow="jk">
<!--    v-slot:st是vue3写法 slot="st"是vue2写法 -->
    <template v-slot:st>这是具名插槽放置在子组件slot</template>
</cp>
</template>

<script>
    import cp from './cp.vue'
    export default{
        data(){
            return{
                "f":""
            }
        },
        methods:{
            jk(msg,fdf){
                this.f=msg+fdf
            }
        }
        ,
        components:{
            cp
            
        }
        
    }
</script>

<style>
</style>

相关文章

网友评论

      本文标题:vue 插槽

      本文链接:https://www.haomeiwen.com/subject/ageeirtx.html