了解和使用 Vue.js 插槽 Slots

发布于 2022-07-29 00:10:57 字数 2767 浏览 169 评论 0

Slots 允许您在 Vue 组件中嵌入任意内容。 Slots 相当于 Vue 中的 Angular 中的嵌入 React 中的子道具

例如,假设您想要一个名为 green 在子内容后面添加了绿色背景。 这是使用插槽的此类组件的示例。

Vue.component('green', {
  // The `<slot></slot>` part will be replaced with child content.
  template: `
    <div style="background-color: #00ff00">
      <slot></slot>
    </div>
  `
});

const app = new Vue({
  // The `<h1>` is the child content.
  template: `
    <green>
      <h1>Hello, World!</h1>
    </green>
  `
});

您还可以定义默认的内部 HTML。 如果下面没有内部 HTML <green></green>,Vue 会使用内部的 HTML <slot></slot> 如下所示。

Vue.component('green', {
  // The inner HTML of `<slot></slot>` is the default.
  template: `
    <div style="background-color: #00ff00">
      <slot>
        <h2>Hello, World!</h2>
      </slot>
    </div>
  `
});

const app = new Vue({
  // No inner HTML
  template: `<green></green>`
});

命名槽

有时您需要多个插槽。 例如,假设您正在编写一个 brand 具有两个插槽的组件,name 和 logo。

Vue.component('brand', {
  // 2 slots named 'logo' and 'name'.
  template: `
    <div class="brand">
      <div class="logo">
        <slot name="logo"></slot>
      </div>
      <div class="name">
        <a href="/">
          <slot name="name"></slot>
        </a>
      </div>
    </div>
  `
});

const app = new Vue({
  // `template v-slot:name` is how you insert content into a slot named
  // 'name'
  template: `
    <brand>
      <template v-slot:logo>
        <img src="https://www.wenjiangs.com/wp-content/uploads/2022/docimg16/logo.png">
      </template>
      <template v-slot:name>
        Mastering JS
      </template>
    </brand>
  `
});

输出 HTML 如下所示:

<div data-server-rendered="true" class="brand">
  <div class="logo">
    <img src="https://www.wenjiangs.com/wp-content/uploads/2022/docimg16/logo.png">
  </div>
  <div class="name">
    <a href="/">
      Mastering JS
    </a>
  </div>
</div>

这是呈现的 HTML:


Mastering JS

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据

关于作者

执妄

暂无简介

0 文章
0 评论
22 人气
更多

推荐作者

不再见

文章 0 评论 0

真是无聊啊

文章 0 评论 0

樱娆

文章 0 评论 0

浅语花开

文章 0 评论 0

烛光

文章 0 评论 0

绻影浮沉

文章 0 评论 0

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文