【Vue】slot插槽使用

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/TheBestAge/article/details/89302305

 slot相当于是一个占位的东西,在插槽里可以放置任何内容。
 slot最简单的使用方式就是在我们的子组件内使用特殊的slot元素为这个子组件开启一个slot,在父组件的模板中,插入这个子组件标签内的所有内容都将代替子组件的slot标签以及它的内容.
 当父组件向子组件传值的时候,有时候,父组件传的并不是单纯的数值,字符串,有可能是带标签(DOM)的数据,所以使用slot来进行此操作

一、简单使用:

父组件内容如下:
<template>
 <login>你好</login>
</template>

<script>
import login from "./login"
export default {
  name: 'HelloWorld',
    components:{
    login,
  },
 }
</script>
...
子组件内容如下:
<template>
    <div> 
        <span>欢迎登陆!</span>       
    </div>
</template>

运行结果如下:
        在这里插入图片描述
在子组件中使用slot:

<template>
    <div> 
        <slot></slot>
        <span class="login">欢迎登陆!</span>      
    </div>
</template>

         在这里插入图片描述

二、具名插槽:

父组件内容如下:
<templete>
  <login> 
    <templete slot="tip">你好</templete>
    <templete slot="CardNo">账号:
       <input type="CardNo">  
    </templete>
    <templete slot="password">密码: 
      <input type="password" >
    </templete>
  </login>
</templete>
子组件:
<template>
    <div> 
        <slot name="tip"></slot>
        <span>欢迎登陆!</span>   
        <div><slot name="CardNo"></slot></div> 
        <div><slot name="password"></slot></div> 
    </div>
</template>

效果图:
在这里插入图片描述

三、作用域插槽:

使用作用域插槽不仅可以在子组件中动态地放置一段html代码片段,还可以取到子组件中相应的一些值。一般情况下,我们在父组件中完成给子组件的数据传递,然后子组件进行渲染。而作用域插槽,父组件只需要提供一套样式

父组件:
<template>
    <template slot-scope="props">
   	 <ul>
      	<li>{{props.item}}</li>
      </ul>
    </template>
  </login>
</template>
子组件:
<template>
    <div> 
        <slot v-for="item of list" :item="item"> 
        </slot>
    </div>
</template>

<script>
export default {
    data(){
        return{
            list:[1,2,3,4],
        }
    },
}
</script>

效果图:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/TheBestAge/article/details/89302305