vue插槽v-slot

1.什么是slot

	<app>
        <menu-main></menu-main>
        <menu-sub></menu-sub>
        <div>
          <app-footer></app-footer>
        </div>
    </app>

为例,在中混合了父组件的内容和子组件的模板时,就会用到slot,这个过程叫做内容分发。
使用slot的组件有两个特点:
1.它创建时不知道某个部分需要挂载什么,这部分内容需要父组件调用时决定。
2.组件可能有它自己的模板。

编译作用域

//父组件
<child-component v-show="show">
     {
     {
     messge}}
</child-component>
//子组件child-component
<template>
	<h1>{
     {
     title}}</h1>
	<div>
		<slot></slot>
	</div>
</template>

在上述代码中,父组件引用child-component子组件,{ {message}}就是一个插槽slot,它绑定的时父组件的数据,而不是子组件的数据。所以它是在父组件的作用域中编译。v-show绑定的参数show也是父组件的数据。
{ {title}}是子组件的数据,所以它是在子组件的作用域中编译。

slot用法

slot分成三类: 匿名插槽、具名插槽、作用域插槽

匿名插槽与具名插槽

有时候我们在组件中希望使用多个插槽,为了能识别父组件传入的插值数据在正确的位置,我们可以给slot加上name,以便区分。
例如组件

<div class="container">
  <header>
    <!-- 我们希望把页头放这里 -->
  </header>
  <main>
    <!-- 我们希望把主要内容放这里 -->
  </main>
  <footer>
    <!-- 我们希望把页脚放这里 -->
  </footer>
</div>

它希望有三处插槽。我们可以这么定义

<div class="container">
  <header>
    <slot name="header"></slot>
  </header>
  <main>
    <slot></slot>
    //或者
    <slot name="default"></slot>
  </main>
  <footer>
    <slot name="footer"></slot>
  </footer>
</div>

这些带有name的插槽,我们就叫做具名插槽。没有带有name的()我们称为匿名插槽。

父元素调用:

<base-layout>
// 会被渲染到
  <template v-slot:header>
    <h1>Here might be a page title</h1>
  </template>
// 会被渲染到
  <p>A paragraph for the main content.</p>
  <p>And another one.</p>
// 会被渲染到
  <template v-slot:footer>
    <p>Here's some contact info</p>
  </template>
</base-layout>

我们在一个 元素上使用 v-slot 指令,并以 v-slot 的参数的形式提供其名称,现在