• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

Vue3插槽

武飞扬头像
lucky_full
帮助1


前言

slot元素是一个插槽出口 (slot outlet),标示了父元素提供的插槽内容 (slot content) 将在哪里被渲染。


一、Vue3插槽

如果父组件引入子组件,并且想在子组件中展示添加内容,这时就可以使用插槽技术

1.匿名插槽

匿名插槽就是没有名字的插槽
代码如下(示例):

// 父组件
<template>
<div>
//引入子组件
	<Child>
		我是需要子组件展示的内容
	</Child>
</div>
</template>

// 子组件
<template>
	<div>
	//添加插槽使父组件写入的内容展示
		<slot></slot>
	</div>
</template>

学新通

2.具名插槽

就是有名字的插槽,父组件写入内容的名字,和子组件slot插槽的名字,对应才会展示。

// 父组件
<template>
<div>
//引入子组件
	<Child>
		<template v-slot:aaa>
			我是需要子组件展示的内容1
		</template>
		<template v-slot:bbb>
			我是需要子组件展示的内容2
		</template>
	</Child>
</div>
</template>

// 子组件
<template>
	<div>
	//添加插槽使父组件写入的内容展示
		<slot name="aaa"></slot>
		<slot name="bbb"></slot>
	</div>
</template>

学新通

此时父组件的aaa对应子组件slot的名字aaa,这时对应的内容就会展示在子组件插槽aaa中,bbb同理。
注意:v-slot:aaa有简写

// 父组件
<template>
<div>
//引入子组件
	<Child>
		<template #aaa>
			我是需要子组件展示的内容1
		</template>
		<template #bbb>
			我是需要子组件展示的内容2
		</template>
	</Child>
</div>
</template>

// 子组件
<template>
	<div>
	//添加插槽使父组件写入的内容展示
		<slot name="aaa"></slot>
		<slot name="bbb"></slot>
	</div>
</template>

学新通

3.作用域插槽

然而在某些场景下插槽的内容可能想要同时使用父组件域内和子组件域内的数据。要做到这一点,我们需要一种方法来让子组件在渲染时将一部分数据提供给插槽。
我们也确实有办法这么做!可以像对组件传递 props 那样,向一个插槽的出口上传递 attributes

// 父组件
<template>
<div>
//引入子组件
	<Child>
		<template v-slot="{data}">
			//可以展示子组件传过来的值
			{{data.name}}
		</template>
	</Child>
</div>
</template>

// 子组件
<template>
	<div>
	//添加插槽使父组件写入的内容展示
		<div v-for="item in arr" :key="item.id">
		//传入一个属性,父组件可以接受并渲染出来
			<slot :data="item"></slot>
		</div>
	</div>
</template>
<script setup>
let arr = ref([
	 {
        name:"aaa",
        age:1,
        id:1
    },
     {
        name:"bbb",
        age:114,
        id:2
    },
     {
        name:"ccc",
        age:6,
        id:3
    }
])
</script>

学新通

作用域插槽也有简写v-slot=“{data}”,可以写为#default=“{data}”

4.动态插槽

根据状态的值动态改变的插槽
代码如下(示例):

// 父组件
<template>
<div>
//引入子组件
	<Child>
	//[str]即为状态str的值
		<template v-slot:[str]>
			我是需要子组件展示的内容1
		</template>
	</Child>
</div>
</template>
<script setup>
let srt = ref("ccc")
</script>
// 子组件
<template>
	<div>
	//添加插槽使父组件写入的内容展示
		<slot name="ccc"></slot>
	</div>
</template>

学新通

这个也有简写v-slot:[str], 可以简写为#[str]

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhgcjekb
系列文章
更多 icon
同类精品
更多 icon
继续加载