插槽用法

268 阅读1分钟

插槽

默认插槽

默认插槽是最原始的插槽

image.png

image.png

  1. slot标签放在子组件中
  2. tempalte标签放在父组件模板插入的子组件标签中

具名插槽

<!-- 具名插槽 -->
    <slotChildren>
      <template v-slot:name1>
        <div>我是具名插槽1</div>
      </template>
      <template slot="name2">
        <div>我是具名插槽2</div>
      </template>
    </slotChildren>    

    <slot name="name1"></slot>
    <slot name="name2"></slot>

具名插槽有两种定义插槽名的方法

  1. v-slot:插槽名
  2. slot="插槽名"

子组件引用插槽

 <slot name="插槽名"></slot>

v-slot可以简写为#

作用域插槽

父 父组件中的scope包含row对象

 <!-- 作用域插槽 -->
 完整写法
    <slotChildren>
      <template v-slot="scope">
        <div>
          {{ scope.row.title2 }}
        </div>
      </template>
    </slotChildren>
    将数据解构
     <slotChildren>
      <template v-slot="{ row }">
        <div>
          {{ row.title2 }}
        </div>
      </template>
    </slotChildren>
    v-solor替换成scope
    <slotChildren>
      <template scope="{row}">
        <div>
          {{ row.name }}
        </div>
      </template>
    </slotChildren>

  <slot :row="myuser"></slot>
  //data中的数据
    data() {
    return {
      myuser: {
        name: "航崽",
        title2: "我是作用域插槽title2",
      },
    };
  },

插槽的作用

插槽可以实现将标签或其他文本插入到子组件中,默认插槽是最简洁的插槽,如果我们要选择性插入子组件了某个位置,我们可以选择具名插槽v-slot:""或slot=""都行,插槽也可以传值给父组件选择性调用子组件中的数据,这就是我们的作用域插槽,作用域插槽用得最多的地方就是我们的组件。