前端包浆记

VUE.js学习笔记--简单理解标签

2019-03-04  本文已影响0人  水云楼

slot

官方称之为”插槽”,我理解就是像是内存插槽的意思,我在子组件里提供这么一个<slot>标签(相当于主板提供的内存插槽)至于插入什么内容(插几G的内存)那是父组件需要提供的(由主机配置决定)。举个栗子:
我们继续改造一下之前的<li-test>的案例:

<template>
<div>
    <input class = 'aaa' v-model.trim="inputValue"/>
    <button @click="handleSubmit">提交</button>
    <span>{{inputValue}}</span>
    <ul>
        <li-test 
            v-for="(item,index) of list" 
            :key="index"
            :content='item'
            :index='index'
            @delete='handleDelete'
        >显示的是传递到子组件中,循环出来的item内容哦</li-test>
    </ul>
    <!-- 即使 Alt 或 Shift 被一同按下时也会触发 -->
    <button @click.middle ="onClick">A</button>
</div>
</template>

我们改造了一下父组件,在调用子组件<li-test>的模板时在里面增加一段话


执行后,原来新加的话被替换了

执行后可以看出,展示的是模板里的内容,我们在父组件里加的其实已经被替换掉了,但如何让他显示呢?这就需要<slot>插槽啦
修改li-test.vue组件:

<template>
<div>
    <li class='aaa' @click="handleDelete">{{content}}</li>
    <slot></slot>
</div>
</template>

子组件模板中我们加入<slot>组件:


可以看到<slot>标签直接替换成了我们在父组件增加的话啦

具名slot

上面的例子描述了简单的slot标签如何使用,但是有些场景下一个slot可能不能满足我们的组件需求,对于这样的情况,<slot> 元素有一个特殊的特性:name。这个特性可以用来定义额外的插槽:官网案例:

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

一个不带 name 的 <slot> 出口会带有隐含的名字“default”。
在向具名插槽提供内容的时候,我们可以在一个 <template> 元素上使用 v-slot 指令,并以 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>

现在 <template> 元素中的所有内容都将会被传入相应的插槽。任何没有被包裹在带有 v-slot 的 <template> 中的内容都会被视为默认插槽的内容。我们也可以用v-slot: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>

备注:v-slot: 可以缩写为”#”,但是该缩写只有在其有参数的时候才可用,以下方法是不可取的:

<!-- 这样会触发一个警告 -->
<current-user #="{ user }">
  {{ user.firstName }}
</current-user>

如果你希望使用缩写的话,你必须始终以明确插槽名取而代之:

<current-user #default="{ user }">
  {{ user.firstName }}
</current-user>
上一篇 下一篇

猜你喜欢

热点阅读