浅谈v-slot插槽

1,849 阅读1分钟

今天看朋友的项目中看到用了v-slot,表示本吊从来没用过,就突然了解了下。

首先对组件的理解,就是父组件用子组件的内容,把子组件塞到父组件内。

插槽正好跟组件相反,是父组件内的一块东西塞到子组件内。

此为vue2.6之前的用法,可不看。(已废弃)

1、slot 组件传标签(父->子)

父组件

<template>
    <div class='father'>
        <!--子组件-->
        <child>
            <div class="item" slot='slot1'>父组件内容1</div>
            <div class="item" slot='slot2'>父组件内容2</div>
            <div class="item" slot='slot3'>父组件内容3</div>
        </child>
    </div>
</template>

slot='slot1'slot1相当于id,子组件会根据这个来找到父组件的元素来进行匹配 子组件

<template>
    <div class='child'>
        <!--slot-->
        <slot name = 'slot1'></slot>
        <slot name = 'slot2'></slot>
        <slot name = 'slot3'></slot>
    </div>
</template>
  • 总结: 这个是父组件把自己内的元素传给子组件,样式只能由子组件内的css来修改。

2、v-slot

此为vue2.6之后的用法(重要)

  • 此版本舍弃了 slotslot-scope
  • v-slot 可缩写为#

2.1 匿名插槽

默认只有一个,不需要命名

  • 父组件 fahterSlot
    <h1>下面是插槽内容</h1>
    <div style="border: solid 1px red">
      <childSlot> <!--子组件-->
        <template v-slot:default>
          我是父组件内容...
        </template>
      </childSlot>
    </div>
  • 子组件 childSlot
  <div class="p-child-slot">
    	我是子组件的内容
   	<slot></slot><!--这里就是父组件传进来的东西,父组件template的内容-->
  </div>

2.2 具名插槽

带有名字的,多个插槽

  • 父组件 fahterSlot
      <childSlot>
        <template v-slot:fatherContentA>
          我是父组件内容A
        </template>
        <template v-slot:fatherContentB>
          我是父组件内容B
        </template>
      </childSlot>
  • 子组件 childrenSlot
  <div class="p-child-slot">
        我是子组件的内容
       <slot name="fatherContentA"></slot><!--输出-我是父组件内容A-->
       <slot name="fatherContentB"></slot><!--输出-我是父组件内容B-->
  </div>

2.3 作用域插槽(传值)

需要传值的插槽,子组件的值传到父组件

  • 子组件 childrenSlot html
  <div class="p-child-slot">
    我是子组件的内容
   <slot name="fatherContentA" :childVal="childVal"></slot>
   <slot name="fatherContentB"></slot>
  </div>

script

    data() {
      return {
        childVal: 100
      }
    },
  • 父组件 fahterSlot
      <childSlot>
        <template v-slot:fatherContentA="childValObj"><!--这里childValObj只是一个变量名,随便命名-->
          我是父组件内容A {{childValObj}}<!--输出{childVal:100}-->
        </template>
        <template v-slot:fatherContentB>
          我是父组件内容B
        </template>
      </childSlot>