Slot插槽使用

基本使用

父组件向子组件里插入一些内容

子组件

<template>
  <a :href="url">
    <slot>
      默认内容,即父组件没有设置内容时,这里显示
    </slot>
  </a>
</template>

<script>
export default {
  props: {
    url: String
  }
}
</script>

父页面

<template>
  <div>
    <SlotComponents :url="web.url"></SlotComponents>
    <hr />
    <SlotComponents :url="web.url">
      {{web.title}}
    </SlotComponents>
  </div>
</template>

<script>
import SlotComponents from '@/components/SlotComponents.vue'
export default {
  components: {
    SlotComponents
  },
  data () {
    return {
      web: {
        url: 'http://www.baidu.com',
        title: '百度',
        subtitle: '百度一下你就知道'
      }
    }
  }
}
</script>

在这里插入图片描述
父页面获取子组件插槽中的值(作用域插槽)

子组件

在slot新增自定义属性 slotData,这个名词随便写什么,是自定义的。

<template>
  <a :href="url">
    <!-- slotData 是可以自定义名称的 -->
    <slot :slotData="web">
      {{web.title}}
    </slot>
  </a>
</template>

<script>
export default {
  props: {
    url: String
  },
  data () {
    return {
      web: {
        url: 'http://www.google.com',
        title: '谷歌',
        subtitle: '谷歌一下你就知道'
      }
    }
  }
}
</script>

父组件

先写一个template,设置v-slot="自定义名"

然后 父组件的自定义名.子组件的自定义名 即可拿到子组件的数据

<SlotComponents :url="web.url">
  <!-- slotProps 是可以自定义名称的 -->
  <template v-slot="slotProps">
    {{slotProps.slotData}}
  </template>
</SlotComponents>

在这里插入图片描述
具名插槽

有多个slot需要指定使用的情况

子组件

<div class="container">
  <header>
    <slot name="header"></slot>
  </header>
  <main>
    <slot></slot>
    <!-- 相当于<slot name="default"></slot> -->
  </main>
  <footer>
    <slot name="footer"></slot>
  </footer>
</div>

父页面

<base-layout>
  <template v-slot:header>
    <h1>Here might be a page title</h1>
  </template>

  <p>A paragraph for the main content.</p>
  <p>And another one.</p>
  <!-- 
		相当于
		<template v-slot:default>
      <p>A paragraph for the main content.</p>
      <p>And another one.</p>
    </template>
	-->
  <template v-slot:footer>
    <p>Here's some contact info</p>
  </template>
</base-layout>
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值