vue slot使用

342 阅读2分钟

Vue slot插槽的使用

参考文献1

参考文献2

Slot 通俗的理解就是“占坑”,在组件模板中占好了位置,当使用该组件标签时候,组件标签里面的内容就会自动填坑(替换组件模板中slot位置)

一、内容插槽

举例:

定义两个组件 home.vuetest.vue 然后在home.vue组件中引用test.vue组件

//home.vue
<test>
    <!-- 添加一个 Font Awesome 图标 -->
    <span class="fa fa-user"></span>
    <!-- 添加一个图标的组件 -->
    <font-awesome-icon></font-awesome-icon>
    Hello Word
</test>
//test.vue
<a href="#">
	 <slot></slot>
</a>

在插槽中使用数据

插槽跟模板其他地方一样都可以访问相同的实例属性(也就是相同的"作用域"),而不能访问<test>的作用域

规则: 父级模板里的所有内容都是在父级作用域中编译的;子模板里的所有内容都是在子作用域中编译的。

二、默认插槽(匿名)

需要给插槽设置一个具体的默认内容,当别的组件没有给你内容的时候,那么默认的内容就会被渲染

//test.vue
//在slot插槽里设置默认内容 Submit
<button>
  <slot>Submit</slot>
</button>

home.vue里直接使用test.vue如下:

//home.vue
<test></test>

那么最后设置的默认内容 Submit 将会被渲染

<button>
   Submit
</button>

假如我们提供内容呢?

//home.vue
<test>按钮</test>

那么这个提供的内容将会替代默认的内容被渲染出来

<button>
   按钮
</button>

三、具名插槽

有时候我们一个组件里需要多个插槽

<slot>元素有一个特殊的特性:name ,这个特性可以用来定义额外的插槽

<div>
  <header>
    <slot name="header"></slot>
  </header>
  
  <main>
    <slot></slot>
  </main>
  
  <footer>
    <slot name="footer"></slot>
  </footer>
</div>

在向具名插槽提供内容的时候,我们可以在<template>元素上使用v-slot指令,并以参数的形式提供其名称

<div>
   <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:footer>
    <p>Here some contact info</p>
  </template>
</div>

多个具名插槽的使用:多个具名插槽,插槽的位置不是使用插槽的位置而定的,是在定义的时候的位置来替换的

四、作用域插槽

就是用来传递数据的插槽

当你想在一个插槽中使用数据时,要注意一个问题作用域的问题。

为了让子组件中的数据在父级的插槽内容中可用,我们可以将数据作为元素的一个特性绑定上去: v-bind:usertext="user"

//test.vue
<div>
	<slot v-bind:usertext="user">{{user.lastName}}</slot>
</div>

data() {
  return{
	user:{
	  firstName:"Fan",
	  lastName:"Jun"
	}
  }
}
//home.vue
<div>
  <test v-slot:default="slotProps">
    {{slotProps.usertext.firstName}}
  </test>
</div>

绑定在 <slot> 元素上的特性被称为插槽 prop

在父组件中,我们可以用 v-slot 设置一个值来定义我们提供的插槽 prop 的名字,然后直接使用(slotProps

父页面在组件标签内插入任意内容,子组件内插糟slot控制摆放位置。