vue具名插槽,作用域插槽详解

1. 1 具名插槽

案例1:有时我们需要多个插槽。例如对于一个带有如下模板的 <base-layout> 组件 (vue官网案例)
<div class="container">
  <header>
    <!-- 我们希望把页头放这里 -->
  </header>
  <main>
    <!-- 我们希望把主要内容放这里 -->
  </main>
  <footer>
    <!-- 我们希望把页脚放这里 -->
  </footer>
</div>

child子组件中的使用:slot 元素有一个特殊的 attribute:name。这个 attribute 可以用来定义额外的插槽

<!-- 子组件 -->
<div class="container">
  <header>
    <slot name="header"></slot>
  </header>
  <main>
    <slot></slot>
  </main>
  <footer>
    <slot name="footer"></slot>
  </footer>
</div>

father父组件中的使用:在向具名插槽提供内容的时候,我们可以在一个 元素上使用 v-slot 指令,并以 v-slot 的参数的形式提供其名称

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

  <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>

渲染结果:

<div class="container">
  <header>
    <h1>Here might be a page title</h1>
  </header>
  <main>
    <p>A paragraph for the main content.</p>
    <p>And another one.</p>
  </main>
  <footer>
    <p>Here's some contact info</p>
  </footer>
</div>

1.2 具名插槽(缩写)

跟 v-on 和 v-bind 一样,v-slot 也有缩写,即把参数之前的所有内容 (v-slot:) 替换为字符 #。例如 v-slot:header 可以被重写为 #header:

<base-layout>
  <template #header>
    <h1>Here might be a page title</h1>
  </template>

  <p>A paragraph for the main content.</p>
  <p>And another one.</p>

  <template #footer>
    <p>Here's some contact info</p>
  </template>
</base-layout>

2. 作用域插槽

  1. 作用域解析: 对于children子组件的作用域就是其父组件下的作用域(作用域的划分:看最外层的模板的作用域),对于如下代码里面的 arr 变量就是访问到父组件data里面的数据;如果我们要在father父组件里面访问到children子组件里面的数据要如何实现呢?
<!-- 父组件 -->
<template>
	<div>
		<children>
			<span v-for="(itme,index) in arr" :key={index}>{
   
   {item}}<span>
		</children>
	</div>
</template>

<script>
export default {
      
      
	data(){
      
      
		return {
      
      
			arr: ['php','java','python','javascript']
		}
	}
</script>

  1. 作用域插槽的目的 让父组件能够访问子组件中才有的数据!!!(借助插槽实现)

children子组件代码

<template>
  <div>
	<span>
	  <slot v-bind:user="user"></slot>
	</span>
  </div>
</template>

<script>
export default {
    
    
	data(){
    
    
		return {
    
    
			user:{
    
    
				name:'李明'
			}
		}
	}
}

子组件: 将 user 作为 < slot >元素的一个 attribute 绑定上去

father父组件代码

<template>
  <div>
	<children>
		<template v-slot:default="slotProps">
		    {
    
    {
    
     slotProps.user.name}}
		  </template>
	</children>
  </div>
</template>

<script>
export default {
    
    
	data(){
    
    
		return {
    
    
		}
	}
}

父组件:绑定在 < slot > 元素上的 attribute 被称为插槽 prop。现在在父级作用域中,我们可以使用带值的 v-slot 来定义我们提供的插槽 prop 的名字 ,slotProps包含了所有的插槽prop

vue官网插槽章节

猜你喜欢

转载自blog.csdn.net/qq_45331969/article/details/127275583