返回介绍

二、插槽统一

发布于 2024-04-04 21:33:24 字数 3233 浏览 0 评论 0 收藏 0

移除 this.$scopedSlots

将所有 this.$scopedSlots 替换为 this.$slots

将所有 this.$slots.mySlot 替换为 this.$slots.mySlot()

1. Vue 2.x

当使用渲染函数,即 h 时,2.x 曾经在内容节点上定义 slot 数据 property。

// 2.x 语法
h(LayoutComponent, [
  h('div', { slot: 'header' }, this.header),
  h('div', { slot: 'content' }, this.content)
])

此外,可以使用以下语法引用作用域插槽:

// 2.x 语法
this.$scopedSlots.header

元素渲染方面

<template slot="t1" slot-scope="scope">
	<div>
    具名插槽 t1,数据{{scope.data}}
  </div>
</template>
<!-- 或者 v-slot -->
<template v-slot:t1="scope"> <!-- 简写:#t1="scope" -->
	<div>
    具名插槽 t1,数据{{scope.data}}
  </div>
</template>

2. Vue 3.x

在 3.x 中,插槽以对象的形式定义为当前节点的子节点:

// 3.x Syntax
h(LayoutComponent, {}, {
  header: () => h('div', this.header),
  content: () => h('div', this.content)
})

当你需要以编程方式引用作用域插槽时,它们现在被统一到 $slots 选项中了。

// 2.x 语法
this.$scopedSlots.header

// 3.x 语法
this.$slots.header()

元素渲染方面

移除 slotslot-scope,仅仅保留使用 v-slot

<template v-slot:t1="scope"> <!-- 简写:#t1="scope" -->
	<div>
    具名插槽 t1,数据{{scope.data}}
  </div>
</template>

具名插槽

# 子组件
<div>
  <slot name="header"></slot>
  <slot></slot>
  <slot name="footer"></slot>
</div>

# 父组件
<Dialog>
  <template v-slot:header>
  	<div>1</div>
  </template>
  <template v-slot>
  	<div>2</div>
  </template>
  <template v-slot:footer>
		<div>3</div>
  </template>
</Dialog>

作用域插槽

在子组件动态绑定参数 派发给父组件的 slot 去使用

<div>
  <slot name="header"></slot>
  <div>
    <div v-for="item in 100">
      <slot :data="item"></slot>
    </div>
  </div>
  <slot name="footer"></slot>
</div>

父组件结构取值

<Dialog>
  <template #header>
		<div>1</div>
  </template>
  <template #default="{ data }">
		<div>{{ data }}</div>
  </template>
  <template #footer>
		<div>3</div>
  </template>
</Dialog>

动态插槽

插槽可以是一个变量名

<template>
	<Dialog>
  	<template #[name]>
    	<div>
      	23
  		</div>
		</template>
	</Dialog>
</template>
<script setup>
	const name = ref('header')
</script>

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文