vue关于插槽的知识

一、基本使用

子组件 childComponent.vue

<template>
    <div>
      <slot name="isscope" :data="data" />
    </div>
</template>
<script>
export default {
  name: 'childComponent',
   ... ...
}
</script>

父组件 parentComponent.vue

<template>
  <childComponent>
    // 写法一:通过slot-scope来获取子组建的值
    <span slot="isscope" slot-scope="item">
        父组件拿值{{item}}
    </span>
    // 写法二:# 等价于 v-slot,#isscope => v-slot:isscope, #isscope="子组件值" => v-slot:isscope="子组件值"
    <template #isscope="item">
        父组件拿值{{item}}
    </template> 
  </childComponent>
</template>
<script>
export default {
  name: 'parentComponent',
   ... ...
}
</script>

二、v-slot指令动态绑定属性

子组件 childComponent.vue

<template>
    <div>
      <slot name="test1" :data="data" />
      <slot name="test2" :data="data" />
      <slot :data="data" />
    </div>
</template>
<script>
export default {
  name: 'childComponent',
   ... ...
}
</script>
2.1、父组件,单个变量名使用
<template>
  <childComponent>
    <template v-slot:[slotName]>
        父组件
    </template>
  </childComponent>
</template>
<script>
export default {
  name: 'parentComponent',
  data() {
    return {
      slotName: 'test1'
    }
  }
}
</script>
2.2、父组件,循环变量名使用
<template>
  <childComponent>
    <template v-for="(name, index) in slotNames" v-slot:[name]="item">
          <div :key="index">
              父组件拿值{{item}}
          </div>
      </template>
  </childComponent>
</template>
<script>
export default {
  name: 'parentComponent',
  data() {
    return {
      slotNames: [ 'test1', 'test2', 'default']
    }
  }
}
</script>

三、组件套组件插槽使用

子组件 childComponent.vue

<template>
    <div>
      <slot name="test1" :data="data" />
      <slot name="test2" :data="data" />
      <slot :data="data" />
    </div>
</template>

父组件 parentComponent.vue

<template>
  <childComponent>
    <template v-for="(name, index) in slotNames" v-slot:[name]="item">
          <div :key="index">
              父组件拿值{{item}}
          </div>
      </template>
  </childComponent>
</template>
<script>
export default {
  name: 'parentComponent',
  data() {
    return {
      slotName:  [ 'test1', 'test2', 'default']
    }
  }
}
</script>

爷爷组件 grandpaComponent.vue

<template>
  <parentComponent>
      // 方法一
      <span slot="test1" slot-scope="item">
          爷爷组件拿值{{item}}
      </span>
    // 方法二
    <template #test1="item">
        爷爷组件拿值{{item}}
      </template> 
  </parentComponent>
</template>
<script>
export default {
  name: 'grandpaComponent',
  ... ...
}
</script>
  • 10
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值