简述Vue的普通Slot以及作用域Slot的区别 ?

在 Vue.js 中,插槽 (slot) 是一种非常重要的内容分发技术,它允许我们在组件模板中嵌入任意内容,使得组件更加复用和可定制。

  1. 普通插槽:普通插槽是最基本的插槽类型。在子组件模板中,我们可以使用 <slot></slot> 标签定义一个插槽,然后在父组件中,我们可以在子组件标签内部写入内容,这些内容会被渲染到子组件的 <slot></slot> 的位置。

例如:

<!-- 子组件 -->
<template>
  <div>
    <slot></slot>
  </div>
</template>

<!-- 父组件 -->
<template>
  <child-component>
    <h1>Hello, Vue!</h1>
  </child-component>
</template>

在这个例子中,<h1>Hello, Vue!</h1> 将会被渲染到子组件的 <slot></slot> 的位置。

  1. 作用域插槽:作用域插槽是一种更高级的插槽类型,它允许子组件将数据传递给插槽。在子组件模板中,我们可以使用 <slot> 标签并添加一个特殊的 v-bind 指令来传递数据,然后在父组件中,我们可以使用一个带有 slot-scope 属性的 <template> 元素来接收数据。

例如:

<!-- 子组件 -->
<template>
  <div>
    <slot v-bind:user="user"></slot>
  </div>
</template>

<script>
export default {
  data() {
    return {
      user: {
        name: 'Alice'
      }
    }
  }
}
</script>

<!-- 父组件 -->
<template>
  <child-component>
    <template slot-scope="{ user }">
      <h1>Hello, {{ user.name }}!</h1>
    </template>
  </child-component>
</template>

在这个例子中,子组件通过 <slot v-bind:user="user"></slot>user 数据传递给插槽,然后父组件通过 <template slot-scope="{ user }"> 接收 user 数据,并在插槽内容中使用它。

总的来说,普通插槽和作用域插槽的主要区别在于,普通插槽只是简单地替换内容,而作用域插槽可以让子组件将数据传递给插槽,使得插槽内容可以访问子组件的数据。

发表评论

后才能评论