Vue2.6+ 插槽新语法

插槽一共就三大类

  • 1.匿名插槽(也叫默认插槽): 没有命名,有且只有一个
  • 2.具名插槽: 相对匿名插槽组件slot标签带name命名的
  • 3.作用域插槽: 子组件内数据可以被父页面拿到(解决了数据只能从父页面传递给子组件)
  • 插槽老的写法已经走在废弃的路上了

匿名插槽

直接上代码
父页面

<div id="father">
  <h1></h1>
  <son>
    <template v-slot:default>
      <p>我会插所有没有名字的插槽</p>
    </template>
  </son>
</div>

子页面

<template id="son">
  <div>
    <h1>儿子</h1>
    <slot></slot>
  </div>
</template>

看一下页面效果
在这里插入图片描述

具名插槽

  <div id="father">
    <h1></h1>
    <son>
      <template v-slot:bottom>
        <p>我是下面的白熊</p>
      </template>
      <template v-slot:top>
        <p>我是上面的棕熊</p>
      </template>
      <template v-slot:center>
        <p>我是中间的熊猫</p>
      </template>
    </son>
  </div>
<template id="son">
  <div>
    <h1>儿子</h1>
    <slot name='top'></slot>
    <slot name='center'></slot>
    <slot name='bottom'></slot>
  </div>
</template>
  • 语法糖
<div id="father">
  <h1>{{ name }}</h1>
  <son>
    <template #bottom>
      <p>我是下面的白熊</p>
    </template>
    <template #top>
      <p>我是上面的棕熊</p>
    </template>
    <template #center>
      <p>我是中间的熊猫</p>
    </template>
  </son>
</div>

在这里插入图片描述

插槽的动态命名

  • 语法
<template v-slot:{动态插槽名}>
  //。。。内容
</template>

作用域插槽

父页面

<div id='father'>
  <h1></h1>
  <son>
    <template #child='sonData'>
      {{ sonData.onedata.name }}
    </template>
  </son>
</div>
  • #child其实是v-slot:child的语法糖写法
  • child要和子组件插槽的name属性一致
  • sonData子组件传过来的所有数据的集合
  • .onedata是在子组件上准备传数据是自定义的一个名字
  • .nameonedata里的一个属性

子页面

<template id='son'>
  <div>
    <h1>儿子</h1>
    <slot name='child' :onedata='one' :twodata='two'></slot>
  </div>
</template>
  • onedata=‘one’里的onedata是给传过去的属性一个自定义名称
  • one是子组件里的数据名
  • 可以用绑定的方式传入多个数据,例如:twodata=‘two’

js代码

const son = {
  template: '#son',
  data() {
    return {
      one: {
        name: '蝎子',
        age: '莱莱'
      },
      two:[1,23,435,5876]
    }
  }
}

const father = new Vue({
  el: '#father',
  components: { son }
})

看一下打印到页面上的效果
在这里插入图片描述

父页面还可以这么写(解构插槽)

<div id='father'>
  <h1></h1>
  <son>
    <template #child='{ onedata,twodata }'>
      {{ onedata.name }}
    </template>
  </son>
</div>

这是由于

  • 作用域插槽的内部工作原理是将你的插槽内容包括在一个传入单个参数的函数里:
function (sonData) {
  // 插槽内容
}

(sonData)=>参数可以用slot标签上现有的值({onedata,twodata})替换

  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值