v-slot的用法以及由来

323 阅读3分钟

前提:一直以来都很少使用跟接触插槽,导致看到一直觉得很陌生,所以决定系统性的去研究一下,然后有了这篇文章。

在 2.6.0 中,我们为具名插槽和作用域插槽引入了一个新的统一的语法 (即 v-slot 指令)。它取代了 slot 和 slot-scope 这两个目前已被废弃但未被移除且仍在文档中的 attribute。新语法的由来可查阅这份 RFC。 :cn.vuejs.org/v2/guide/co…

1.v-slot具名插槽用法

1.1 子组件定义为:

<div>
    <slot name='header' />
</div>

1.2.1父组件像以下这样使用子组件:

<child>
    <template v-slot:header>
        <div>header-text</div>
    </template>
</child>

1.2.2或者父组件像也可以这样简写使用子组件:

<template #header>
    <div>header-text</div>
</template>

1.3渲染出来的 HTML 将会是,如下图:

image.png

2.v-slot作用域插槽用法

子组件模板定义:

<div>
    <slot name='footer' :haha="haha" :data="data">
    </slot>
</div>
export default {
  data () {
    return {
      data: ['zhangsan', 'lisi', 'wanwu', 'zhaoliu', 'tianqi', 'xiaoba'],
      haha: '这个插槽是不是很美妙呢'
    }
  }
}

父组件使用子组件

<child>
   <template v-slot:footer="message">
      <div>{{message.data}}</div>
      <div>{{message.haha}}</div>
   </template>
</child>

效果如下:

image.png

老版本已被废弃,但是任然未被移除

1. slot匿名插槽-老版本用法

1.1 子组件定义为:

<a v-bind:href="url" class="nav-link">
  <slot></slot>
</a>

1.2父组件像以下这样使用子组件:

<navigation-link url="/profile">
  Your Profile
</navigation-link>

1.3渲染出来的 HTML 将会是,如下图:

image.png

其实就是父组件标签中的Your Profile字样放在了子组件的部分,(如果不在子组件中写上,那么父组件使用子组件标签当中夹的东西是不会传递到子组件去的哟,童鞋们可以试一下)所以当我们封装一个子组件的时候,有一个地方经常变化,我们可以把这个地方写成插槽,来实现父组件对公用的子组件某个地方的控制。

发现问题:那么当我们子组件有两个或者多个地方不确定的时候,我们父组件传下去的两块儿哪个放在哪里呢?

那么就有了如下部分的具名插槽

2.slot具名插槽-老版本

需要多个插槽时,可以利用 元素的一个特殊的特性:name来定义具名插槽 2.1子组件模板定义:

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

2.2.1父组件使用子组件,节点上使用slot特性:

<base-layout>
  <h1 slot="header">Here might be a page title</h1>

  <p>A paragraph for the main content.</p>
  <p>And another one.</p>

  <strong slot="footer">Here's some contact info</strong>
</base-layout>

2.2也可在内容外层套一个节点,并在外层节点上使用slot特性:

<base-layout>
  <template 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 slot="footer">
    <strong>Here's some contact info</strong>
  </template>
</base-layout>

效果如下

image.png

像我们现在的插槽已经实现了一个组件中多个地方使用插槽,那么现在我们只能使用slot来实现父传子数据,通过props进行接收,那么如果想要实现子传父,难道我们还要通过props写方法或者$emit来实现子组件传递给父组件数据吗,那么这样看着就挺麻烦呢,于是乎,尤大大给我们提供了下面的作用域插槽来实现插槽子传父,下面跟着小编一起看看吧!

3.slot作用域插槽-老版本

单个插槽和具名插槽中插槽上不绑定数据,所以父组件提供的模板既要包括样式又要包括数据,而作用域插槽是子组件提供数据,父组件只需要提供一套样式

子组件模板定义:

<div>
    <slot :data="data" :haha="haha"></slot>
</div>

export default {
  data () {
    return {
      data: ['zhangsan', 'lisi', 'wanwu', 'zhaoliu', 'tianqi', 'xiaoba'],
      haha: '这个插槽是不是很美妙呢'
    }
  }
}

父组件使用子组件

<child>
    <template slot-scope="user">
       <h5>{{user.data}}</h5>
       <h6>{{user.haha}}</h6>
    </template>
</child>

效果如下:

image.png

就这样就使用了slot达到子传父了呢,这样是不是很简便呢

本篇文章如有不正确之处,欢迎评论指出!

参考文献:www.cnblogs.com/vickylinj/p…