Skip to content

具名插槽 ​

本节目标:理解“具名插槽”的核心思路,并能把它用于实际开发或面试表达。

  • ==即使用==name==属性给组件定义的插槽取一个名字;==
  • ==一般只有一个插槽时,不使用====name====属性,不带== name ==的== \<slot\> ==会带有隐含的名字“==default==”;==
  • ==只有在组件内有多个插槽时,我们才定义==name==属性;==
  • ==有==\<template\>==标签上使用指令==v-slot:name==来给组件内对应的插槽传递内容。==

==自== 2.6.0 ==起有所更新。已废弃的使用== slot attribute ==的语法在====这里====。== ==有时我们需要多个插槽。每个插槽放置传递过来的相应值。例如:==

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

==可以的话:==

  • ==在模板的== \<slot\> ==元素上使用==name==这个==

     attribute

    ==来指定接受哪个内容。==

  • ==不带== name ==的== \<slot\> ==会带有隐含的名字“==default==”。==

  • ==在向具名插槽提供内容的时候,可在== \<template\> ==元素上使用== v-slot ==指令,并在== v-slot ==的参数中提供对应==\<slot\>==元素的==name==;==

  • ==任何没有被包裹在带有== v-slot==指令== ==的== \<template\> ==中的内容,都会被视为==default==默认插槽的内容。==

  • v-slot ==只能添加在== \<template\> ==上== (==只有====一种例外情况==)==,这一点和已经废弃的==

    slot

    attribute ==不同。==

  • ==可以使用==#name==来作为==v-slot:name==的简写。==

==例如,在模板中:== ==在向传递相应内容时:==

<base-layout>
  <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's some contact info</p>
  </template>
</base-layout>

==对于==default==插槽:==

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

本站总访问 — 次