Vue

梗概:

  1. 可以在组件外面传递html标签组件内部
  2. 把想要插入slot内的html标签作为目标组件的子html内容 1. 如果时多个html标签,则使用Vue template标签包裹起来
  3. 插槽的作用域在组件外面
  4. 在组件内向<slot>的某个属性绑定一个变量, 可以将这个变量暴露到组件外面
    1. 在外面通过<template v-slot:插槽名="自定义名字">获取若干个暴露变量的包裹对象
      1. 可以直接进行解构
    2. <slot name="插槽名">

实例:

1. 单个插槽:

之一

不使用<template>传递内容到默认插槽

当你想要传递内容到子组件的默认插槽时,可以直接在父组件中写入想要的HTML或组件,而不需要用<template>包裹它们。

<!-- ChildComponent.vue -->
<template>
  <div>
    <slot></slot> <!-- 默认插槽 -->
  </div>
</template>
<!-- ParentComponent.vue -->
<template>
  <ChildComponent>
    <p>This is some default slot content.</p>
    <p>No matter how many html tag, it's ok</p>
  </ChildComponent>
</template>

不使用<template>传递内容到具名插槽

对于具名插槽,如果你只需要传递单个元素或组件,也可以不使用<template>。但你需要在该元素或组件上直接使用v-slot指令(或其缩写#)来指明插槽的名称。

<!-- ChildComponent.vue -->
<template>
  <div>
    <slot name="header"></slot> <!-- 具名插槽 -->
  </div>
</template>
<!-- ParentComponent.vue -->
<template>
  <ChildComponent>
    <h1 v-slot:header>This is a header</h1> <!-- 直接使用v-slot -->
    <!-- 或者使用缩写 -->
    <!-- <h1 #header>This is a header</h1> -->
  </ChildComponent>
</template>

之一

let app = createApp({
  data(){
	return{
	  root:'fuck',
	}
  }
})
app.component('alert-box', {
  data(){
    return{
      word:'hello',
    }
  },
  template: `
    <div class="demo-alert-box">
      <slot>默认内容</slot>
    </div>
  `//当外部没有提供插槽内容的时候,就采用<slot>标签中间的默认内容
}).mount('#app');
<div id="app">
	<alert-box>
	  <h1>Something happened.</h1><!--组件标签的innerHTML将会替换<slot></slot>-->
	  <p>{{root}}</p><!-- "fuck",可以访问到组件的父组件内的变量 -->
	  <p>{{word}}</p><!-- 报错,访问不到组件内部的变量-->
	</alert-box>
<div>

2. 多个插槽:

组件模板:

<div class="container">
  <header>
    <slot name="header"></slot>
  </header>
  <main>
    <slot></slot><!--名字是default-->
  </main>
  <footer>
    <slot name="footer"></slot>
  </footer>
</div>

调用组件:

<base-layout>
  <template v-slot:header><!-- 'v-slot:header' 可以缩写为 '#header' -->
    <h1>Here might be a page title</h1>
  </template>
  <template v-slot:default><!-- 'v-slot:default' 可以缩写为 '#default' -->
    <p>A paragraph for the main content.</p>
    <p>And another one.</p>
  </template>
  <template v-slot:footer>
    <p>Here's some contact info</p>
  </template>
</base-layout>

甚至还可以使用动态插槽名:

<template v-slot:[名字变量]>
</template>

渲染结果:

<div class="container">
  <header>
    <h1>Here might be a page title</h1>
  </header>
  <main>
    <p>A paragraph for the main content.</p>
    <p>And another one.</p>
  </main>
  <footer>
    <p>Here's some contact info</p>
  </footer>
</div>

3. 暴露组件内部变量给插槽:

3.1. 单个插槽:

组件模板:

<slot :test="hello" :name="qql1"></slot>

调用组件:

<my-component v-slot:default="自命名变量"><!-- ":default" 可以忽略 -->
	<div>{{自命名变量.test}}</div><!-- hello -->
</my-component>
 
<!-- 还可以直接解构插槽prop对象 -->
<my-component v-slot="{ name: 别名}">
	<div>{{别名}}</div><!-- qql1 -->
</my-component>

说明:

  1. use::解构