返回

插槽——Vue源码探秘

前端

Vue插槽Slot的奥秘

Vue中的插槽,又称Slot,是组件中用于插入内容的占位符。它允许父组件将子组件作为模板的一部分进行渲染,从而实现模块化和可重用性。插槽Slot的使用非常广泛,从简单的布局到复杂的组件库,无处不在。

插槽Slot的使用

单个插槽

单个插槽是最简单的一种插槽,它允许父组件向子组件传递一个内容片段。父组件可以使用slot属性指定插槽的名称,子组件可以使用slot标签来接收父组件传递的内容。

<template>
  <div>
    <!-- 父组件 -->
    <my-component>
      <p>这是父组件传递的内容</p>
    </my-component>
  </div>
</template>

<script>
export default {
  components: {
    MyComponent: {
      template: '<div><slot /></div>'
    }
  }
}
</script>

匿名插槽编译作用域

匿名插槽编译作用域是指,在子组件中使用匿名插槽<slot />时,其编译作用域是父组件。这意味着,匿名插槽中的变量和方法都可以在父组件中访问。

<template>
  <div>
    <!-- 父组件 -->
    <my-component>
      <template #default>
        <p>{{ message }}</p>
      </template>
    </my-component>
  </div>
</template>

<script>
export default {
  data() {
    return {
      message: 'Hello World!'
    }
  },
  components: {
    MyComponent: {
      template: '<div><slot /></div>'
    }
  }
}
</script>

后备内容

后备内容是指,当子组件没有收到父组件传递的内容时,显示在插槽中的内容。后备内容可以使用<slot>...</slot>标签来定义。

<template>
  <div>
    <!-- 父组件 -->
    <my-component>
      <!-- 后备内容 -->
      <p>这是后备内容</p>
    </my-component>
  </div>
</template>

<script>
export default {
  components: {
    MyComponent: {
      template: '<div><slot>这是后备内容</slot></div>'
    }
  }
}
</script>

具名插槽

具名插槽允许父组件向子组件传递多个内容片段,每个内容片段都有自己的名称。父组件可以使用<slot name="slotName">属性指定插槽的名称,子组件可以使用<slot name="slotName">标签来接收父组件传递的内容。

<template>
  <div>
    <!-- 父组件 -->
    <my-component>
      <p slot="header">这是头部内容</p>
      <p slot="content">这是主体内容</p>
      <p slot="footer">这是尾部内容</p>
    </my-component>
  </div>
</template>

<script>
export default {
  components: {
    MyComponent: {
      template: `
        <div>
          <slot name="header"></slot>
          <slot name="content"></slot>
          <slot name="footer"></slot>
        </div>
      `
    }
  }
}
</script>

结语

插槽Slot是Vue中非常强大的一项特性,它极大地提高了组件的灵活性