关于vue.js:Vue组件slot

插槽分类

  • 默认插槽(匿名插槽)(单个插槽)
  • 具名插槽
  • 作用域插槽

插槽的作用

让父组件能够向子组件指定地位插入html构造,也是一种组件间通信的形式。插槽显示不显示,怎么显示,是父组件及管制。显示在什么地位,是子组件管制。

应用形式

1.默认插槽

// 父组件
<template>
    <div class="father">
        <h3>这里是父组件</h3>
        <child>
            <div class="tmpl">
              <span>菜单1</span>
              <span>菜单2</span>
              <span>菜单3</span>
            </div>
        </child>
    </div>
</template>

// 子组件
<template>
    <div class="child">
        <h3>这里是子组件</h3>
        <slot></slot>
    </div>
</template>

2.具名插槽

// 父组件
<template>
  <div class="father">
    <h3>这里是父组件</h3>
    <child>
      // 这里能够应用v-slot。vue2.6当前提出的,然而,必须写在template下面,否则报错,v-slot能够简写成#
      // <template v-slot:a>
      // <template #a>
      <div class="tmpl" slot="a">
        <span>菜单1</span>
        <span>菜单2</span>
        <span>菜单3</span>
      </div>
      <div class="tmpl" slot="b">
        <span>菜单-1</span>
        <span>菜单-2</span>
        <span>菜单-3</span>
      </div>
      <div class="tmpl">
        <span>菜单->1</span>
        <span>菜单->2</span>
        <span>菜单->3</span>
      </div>
    </child>
  </div>
</template>

// 子组件
<template>
  <div class="child">
    // 具名插槽
    <slot name="a"></slot>
    <h3>这里是子组件</h3>
    // 具名插槽
    <slot name="b"></slot>
    // 匿名插槽
    <slot></slot>
  </div>
</template>

3.作用域插槽

这个插槽,可能有点难了解,然而还是有应用场景的,就是数据不在父组件,而是在子组件中的时候

// 父组件
<template>
  <div class="father">
    <h3>这里是父组件</h3>
    <child>
      // <template scope="childData">
      // 下面是以前的写法,上面是新的写法,都能够
      // 这里必须是template
      <template slot-scope="childData">
        <span v-for="(item,index) in childData.lists" :key="index">{{item}}</span>
      </template>
    </child>
  </div>
</template>

// 子组件
<template>
  <div class="child">
    <slot :lists="list"></slot>
  </div>
</template>

data() {
    return {
        list: ['菜单1','菜单2','菜单3']
    }
}

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理