Vue使用:slot插槽

186 阅读1分钟

slot(父组件向子组件插值)

1. 基本使用

往子组件插入一段内容

2. 作用域插槽

父组件获取子组件内容,通过插槽传进去

子:slotData="", 父:template v-slot="slotProps" {{slotProps.slotData}})

// 父
<message class="success">
  <template v-slot="slotProps">
    <strong>{{slotProps.desc.title}}</strong>
  </template>
</message>
  
// 子:
Vue.component('message', {
      data() {
        return {
           desc: {
             title: "test"
           }
        }
      },
      template: `
        <transition enter-active-class="animated bounceIn"
          leave-active-class="animated bounceOut">
          <div class="message-box" v-if="show">
            <!--作用域插槽-->
            <slot :slotData="desc">默认标题</slot>
          </div>
        </transition>
      `,
      },
      },
    })

3. 具名插槽

父组件 template v-slot定义,子组件定义slot name接收

image.png

// 父
<message ref="msgSuccess" class="success">
  <!-- 命名为title插槽内容 -->
  <template v-slot:title="slotProps">
    <strong>{{slotProps.title}}</strong>
  </template>
  <!-- 默认插槽内容 -->
  <template v-slot:default>
    新增课程成功!
  </template>
</message>

  
// 子:
Vue.component('message', {
      data() {
        return {
           desc: {
             title: "test"
           }
        }
      },
      template: `
        <transition enter-active-class="animated bounceIn"
          leave-active-class="animated bounceOut">
          <div class="message-box" v-if="show">
            <!--具名插槽-->
            <slot name="title" title="来自message的标题">默认标题</slot>
            <!--通过slot获取传入内容-->
            <slot></slot>
          </div>
        </transition>
      `,
      },
      },
    })