• Home
  • Archives
  Evan的博客
  • Home
  • Archives
  • 面试
  • 原理笔记
  • 项目实践
  • 其他

插槽

2020/10/09 posted in  原理笔记

这篇 markdown 记录了:

  1. 插槽的概念
  2. 具名插槽
  3. 作用域插槽

什么是插槽

插槽就是在组件内预留一个 <slot> 标签,用来容纳组件起始标签和结束标签之间的内容。如果没有 <slot> 标签,那么组件起始和结束标签件的内容将会被抛弃

<!-- 自定义一个 navigation 组件 -->
<a v-bind:href="url"
   class="nav-link">
   <!-- 预留一个 slot -->
   <slot></slot>
</a>

<navigation-link url="/profile">
  <!-- 组件内的 html 内容会被加载到 slot 插槽中 -->
  <span>Your Profile</span>
</navigation-link>
  • 插槽允许默认内容,它只会在没有提供内容的时候被渲染。
<!-- submit-button 组件内的插槽提供了默认内容 -->
<button type="submit">
  <slot>Submit</slot>
</button>

<!-- 当不提供内容的情况下,会渲染默认内容 Submit -->
<submit-button></submit-button>

<!-- 提供了内容,会渲染提供的 html: Save -->
<submit-button>Save</submit-button>

具名插槽

插槽有个 name 属性,用于指定插入元素的位置。这种插槽被称为具名插槽。不带 name 属性的插槽默认会以 default 命名。在使用具名插槽时,需要用 template 标签包裹 html 内容,并且用 v-slot 指定对应的插槽位置。

<!-- base-layout 组件 -->
<div class="container">
  <header>
    <!-- 给插槽命名 -->
    <slot name="header"></slot>
  </header>
  <main>
    <!-- 未命名插槽默认是 default -->
    <slot></slot>
  </main>
  <footer>
    <slot name="footer"></slot>
  </footer>
</div>

<!-- 使用 base-layout 组件 -->

<base-layout>
  <!-- 用 template 包裹 html 内容,且 v-slot 指向插槽位置 -->
  <template v-slot:header>
    <h1>Here might be a page title</h1>
  </template>

  <!-- 默认内容会插入 default 插槽 -->
  <p>A paragraph for the main content.</p>
  <p>And another one.</p>

  <template v-slot:footer>
    <p>Here's some contact info</p>
  </template>
</base-layout>

作用域插槽

一般情况下,组件只能访问自己组件内的状态。也就是父组件没办法使用插槽中定义的状态。如果要解决这个问题,就要使用作用域插槽。

<!-- 组件 show-name -->
<template>
  <div>
    <!-- 若想让外部组件访问到 name,就要绑定 name,用 props 的方式抛出去 -->
    <slot :user="name"></slot>
  </div>
</template>
<script>
export default {
  name: "SlotComp",
  data() {
    return {name: "Evan"};
  }
};
</script>

<template>
  <div id="app">
    <!-- 作用域插槽必须指定 v-slot,同时随便给 props 命名,命名后可取值 -->
    <SlotComp v-slot:default="Props">I am {{Props.user}}</SlotComp>
  </div>
</template>

<script>
import SlotComp from "./components/SlotComp";

export default {
  name: "App",
  components: {SlotComp}
};
</script>

« Vue 实例方法 & Vue use

better-scroll 排坑指南 »

Evan的博客

Evan 的博客 - 非典型码农,bug永动机
Instagram Weibo GitHub Email RSS

Categories

面试 原理笔记 项目实践 其他 JS Vue 性能优化 算法 计算机网络

Recent Posts

  • 从 HTTP 发展历程重学计算机网络
  • 应届前端的逆袭(中)
  • 应届前端的逆袭(上)
  • 应届前端的逆袭(下)
  • 前端面经复盘

Copyright © 2015 Powered by MWeb,  Theme used GitHub CSS.