Vue插槽简介和使用示例详解

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

Vue插槽简介和使用示例详解

波波仔86   2023-03-23 我要评论

对于插槽的概念和使用,这是vue的一个难点,这需要我们静下心来,慢慢研究。以下是我这两天通过官网和其他资料的学习和使用总结出来的笔记,如有错误或者有不同见解的,欢迎留言,一起学习。

什么是插槽

插槽就是子组件中的提供给父组件使用的一个占位符,用<slot></slot> 表示,父组件可以在这个占位符中填充任何模板代码,如 HTML、组件等,填充的内容会替换子组件的<slot></slot>标签。

代码如下:

1、在子组件中放一个占位符

<template>
    <div>
        <h1>今天天气状况:</h1>
        <slot></slot>
    </div>
</template>
<script>
    export default {
        name: 'child'
    }
</script>

2、在父组件中给这个占位符填充内容

<template>
    <div>
        <div>使用slot分发内容</div>
        <div>
            <child>
                <div style="margin-top: 30px">多云,最高气温34度,最低气温28度,微风</div>
            </child>
        </div>
    </div>
</template>
<script>
    import child from "./child.vue";
    export default {
        name: 'father',
        components:{
            child
        }
    }
</script>

3、展示效果:

现在来看看,如果插槽中没有放入插槽,同样的父组件中在子组件中填充内容,会是啥样的:

<template>
    <div>
        <h1>今天天气状况:</h1>
<!--        <slot></slot>-->
    </div>
</template>
<script>
    export default {
        name: 'child'
    }
</script>

总结:如果子组件没有使用插槽,父组件如果需要往子组件中填充模板或者html, 是没法做到的

插槽的使用

插槽的最最简单使用,上面已有例子,这里就不写了,接下来看看,插槽其他使用场景

插槽使用 - 具名插槽

描述:具名插槽其实就是给插槽取个名字。一个子组件可以放多个插槽,而且可以放在不同的地方,而父组件填充内容时,可以根据这个名字把内容填充到对应插槽中。代码如下:

1、子组件的代码,设置了两个插槽(header和footer):

<template>
    <div>
        <div class="header">
            <h1>我是页头标题</h1>
            <div>
                <slot name="header"></slot>
            </div>
        </div>
        <div class="footer">
            <h1>我是页尾标题</h1>
            <div>
                <slot name="footer"></slot>
            </div>
        </div>
    </div>
</template>
 
<script>
    export default {
        name: "child1"
    }
</script>
 
<style scoped>
 
</style>

2、父组件填充内容, 父组件通过 v-slot:[name] 的方式指定到对应的插槽中

<template>
<div>
    <div>slot内容分发</div>
    <child1>
        <template slot="header">
            <p>我是页头的具体内容</p>
        </template>
        <template slot="footer">
            <p>我是页尾的具体内容</p>
        </template>
    </child1>
</div>
</template>
 
<script>
    import child1 from "./child1.vue";
 
    export default {
        name: "father1",
        components: {
            child1
        }
    }
</script>
 
<style scoped>
 
</style>

展示效果

参考文献:

https://www.cnblogs.com/mandy-dyf/p/11528505.html

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们