zl程序教程

您现在的位置是:首页 >  前端

当前栏目

Vue中作用域插槽的使用

Vue 作用域 插槽 使用
2023-09-11 14:19:18 时间

Vue中的作用域插槽可以让父组件使用插槽时的内容能够访问子组件中的数据,数据在组件自身,但是根据数据生成的结构需要组件的使用者来决定。

这里可以先看一个例子,以便更好的理解作用域插槽的作用,在子组件中使用v-for创建一个列表循环,然后在父组件中通过子组件标签category调用,如下例。

category子组件:

<template>
	<div class="category">
		<ul>
            <li v-for="(g,index) in games" :key="index">{{g}}</li>
        </ul>
	</div>
</template>

<script>
	export default {
		name:'Category',
		props:['title'],
		data() {
			return {
				games:['红色警戒','穿越火线','劲舞团','超级玛丽'],
			}
		},
	}
</script>

App父组件:

<template>
	<div class="container">

		<Category title="游戏"></Category>

		<Category title="游戏"></Category>

		<Category title="游戏"></Category>
	</div>
</template>

<script>
	import Category from './components/Category'
	export default {
		name:'App',
		components:{ Category },
	}
</script>

结果:

 

 调用了三次category组件,因为调用的是同一个子组件,所以显示的内容完全一样。

 那如何在每次调用时能有各自的渲染效果?这就是作用域插槽的用武之地。

作用域插槽就是父组件在调用子组件的时候给子组件传了一个插槽,这个插槽为作用域插槽,该插槽必须放在template标签里面,同时声明从子组件接收的数据放在一个自定义属性内,并定义该数据的渲染方式,实现从子组件到父组件的数据传递。通过下列展示作用域插槽的使用方式:

category子组件:

<template>
	<div class="category">
		<slot :games="games" msg="hello">我是默认的一些内容</slot>//通过:game传递
	</div>
</template>

<script>
	export default {
		name:'Category',
		props:['title'],
		data() {
			return {
				games:['红色警戒','穿越火线','劲舞团','超级玛丽'],
			}
		},
	}
</script>

App父组件(scope="{对象名(可解构赋值)}"声明):

<template>
	<div class="container">

		<Category title="游戏">
			<template scope="atguigu">
				<ul>
					<li v-for="(g,index) in atguigu.games" :key="index">{{g}}</li>
				</ul>
			</template>
		</Category>

		<Category title="游戏">
			<template scope="{games}">
				<ol>
					<li style="color:red" v-for="(g,index) in games" :key="index">{{g}}</li>
				</ol>
			</template>
		</Category>

		<Category title="游戏">
			<template slot-scope="{games}">
				<h4 v-for="(g,index) in games" :key="index">{{g}}</h4>
			</template>
		</Category>
	</div>
</template>

<script>
	import Category from './components/Category'
	export default {
		name:'App',
		components:{ Category },
	}
</script>

通过上例可知,使用作用域插槽后,三次调用子组件可以定义不同的渲染方式。这里我们使用的数据是一样的,但是根据数据生成的结构是由使用的父组件决定的。数据只通过插槽传递即可,达到了更灵活的效果。games数据在category组件中,但数据遍历出来的结构由App决定。