vue中插槽小结

1、什么是插槽

插槽(Slot)是 Vue 提出来的一个概念,插槽用于决定将所携带的内容,插入到指定的某个位置,具有模块化的特质和更大的重用性。插槽显不显示、怎样显示是由父组件来控制的,而插槽在哪里显示就由子组件来进行控制

2、插槽分类

插槽一般可分为三大类:匿名插槽(默认插槽)、具名插槽、作用于插槽,语法如下:

<slot></slot>

3、匿名插槽使用示例

<template>
    <h1>这是一个子组件</h1>
    <slot></slot>
    <slot></slot>
</template>


<template>
  <h1>这是父组件</h1>
  <Son>
    <p style="color: red;">匿名(默认)插槽数据</p>
    <p style="color: yellow;">匿名(默认)插槽数据</p>
  </Son>
</template>

运行结果:

4,具名插槽使用示例

<template>
    <h1>这是一个子组件</h1>
    <slot name="s"></slot>
</template>

<template>
  <h1>这是父组件</h1>
  <Son>
    <template v-slot='s'>
    <!--简写用‘#’代替‘v-slot’
    <template #s>-->
      <p style="color: greenyellow;">具名插槽</p>
    </template>
  </Son>
</template>

 运行结果:

 5、作用域插槽(可用于子组件向父组件传值)

<template>
    <h1>这是一个子组件</h1>
    <slot name="s" :userInfo="userInfo" :xingming="name"></slot>
</template>

<template>
  <h1>这是父组件</h1>
  <Son>
    <!-- <p style="color: red;">匿名(默认)插槽数据</p>
    <p style="color: yellow;">匿名(默认)插槽数据</p> -->
    <template #s="mprops">
      <p style="color: greenyellow;">具名插槽---{{mprops.userInfo.name}}-----                {{mprops.userInfo.age}}</p>
      <p style="color: greenyellow;">具名插槽---{{mprops.xingming}}</p>
    </template>

  </Son>
</template>


运行结果:

6、动态插槽,这里就不具例子了,其实就是把具名插槽的name用一个变量替代,根据变量取值来觉得用那个具名插槽显示。 

如有不足之处,请提出共同交流学习!

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值