当前位置: 移动技术网 > IT编程>脚本编程>vue.js > vue中插槽的使用详解

vue中插槽的使用详解

2020年07月11日  | 移动技术网IT编程  | 我要评论

插槽也就是slot,是组件中的一块html模板,这模板显示不显示,以及怎样显示由父组件来决定。

插槽的使用场景,个人理解勿喷:当你在父组件中想要操作子组件,往子组件插入html代码片段的时候,这时候插槽的作用就是体现了,如果子组件不设置插槽,父组件是插入不了子组件中的代码片段的。

单个插槽

单个插槽可以放置在组件的任意位置,但是就像它的名字一样,一个组件中只能有一个该类插槽。相对应的,具名插槽就可以有很多个,只要名字(name属性)不同就可以了。
看代码

父组件

  <template>
   <div class='father'>
    <h3>这里是父组件</h3>
    <child>   //使用之前别忘在components里注册子组件
    <span>菜单1</span>  //这里往子组件里插入代码块
     <span>菜单2</span>
     <span>菜单3</span>
    </child>
   </div>
  </template>

子组件

<template id="child">
    <div class="child">
        <h3>这里是子组件</h3>
        <slot></slot>  //如果不设置插槽 不会显示父级中的span标签
    </div>
</template>

在这里插入图片描述

具名插槽

匿名插槽没有name属性,所以是匿名插槽,那么,插槽加了name属性,就变成了具名插槽。具名插槽可以在一个组件中出现N次。出现在不同的位置

父组件

<template> 
<div id="app">
    <div class="father">
        <h3>这里是父组件</h3>
        <child>
            <span>菜单2</span>
            <span slot="demo3">菜单3</span>
        </child>
    </div>
</div>
</template> 

子组件

<template id="child">
    <div class="child">
        <h3>这里是子组件</h3>
        <slot></slot>
        <slot name="demo3"><slot>  //可以定义多个,与父组件solt=‘’对应即可
    </div>
</template>

在这里插入图片描述

作用域插槽

父组件模板的所有东西都会在父级作用域内编译;子组件模板的所有东西都会在子级作用域内编译。
不过,我们可以在父组件中使用 slot-scope 特性从子组件获取数据
前提是需要在子组件中使用 :data=data 先传递 data 的数据

父组件

<template> 
<div id="app">
    <div class="father">
        <h3>这里是父组件</h3>
        <child>
            <template slot-scope="user">  //这里一定要写在template 模板里边 进行传值
             <div >
                {{user.data}}
             </div>
            </template>
        </child>
    </div>
</div>
</template> 

子组件

<template id="child">
    <div class="child">
     <slot :user='data'></slot>
    </div>
</template>
<script>
  data(){
 return {
    data: ['zhangsan', 'lisi', 'wanwu', 'zhaoliu', 'tianqi', 'xiaoba']
 }
 }
</script>

在这里插入图片描述

本文地址:https://blog.csdn.net/qq_46124502/article/details/107261997

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网