vue slot插槽

作者: me_coder | 来源:发表于2019-11-27 10:42 被阅读0次

    作用及作用域

    如果一个组件内没有包含一个<slot>元素,那么该组件标签开始和结束之间的任何内容会被抛弃;
    父级模板里的所有内容都是在父级作用域中编译的;子模板里的所有内容都是在子作用域中编译的。

    用法

    如果想插入多个不同的slot到指定的位置,可以为每个插槽指定一个名字,如下所示:

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

    注:一个不带 name 的 <slot> 出口会带有隐含的名字“default”。
    然后使用v-slot指令,可以具体内容插入到指定的插槽,如下所示:

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

    而没有带v-slot指令的内容会被插入到默认的位置,即default的位置。
    注意 v-slot 只能添加在 <template> 上 ,只有一种例外情况:当被提供的内容只有默认插槽时,如下:

    <current-user>
      <template v-slot:default="slotProps">
        {{ slotProps.user.firstName }}
      </template>
    </current-user>
    

    可以写成:

    <current-user v-slot:default="slotProps">
      {{ slotProps.user.firstName }}
    </current-user>
    

    v-slot:header 可以缩写为 #header,该缩写只在其有参数的时候才可用,即v-slot:default=" "不可写成#=" ",但可以写成#default=“ ”。

    相关文章

      网友评论

        本文标题:vue slot插槽

        本文链接:https://www.haomeiwen.com/subject/uizuwctx.html