vue2中的插槽

在 Vue 2 中,插槽(slots),允许你将父组件的内容传递到子组件中,并在子组件的模板中指定内容的显示位置。

1. 默认插槽

默认插槽是最基础的插槽形式。如果子组件只有一个插槽并且不命名,那么它就是默认插槽。父组件可以通过插槽将内容传递给子组件。

子组件:

<template>
  <div>
    <slot></slot>
  </div>
</template>

父组件:

<template>
  <child-component>
    <p>This is passed to the child component's default slot.</p>
  </child-component>
</template>

2. 具名插槽

具名插槽允许你在子组件中定义多个插槽,并通过名称来指定内容应该放置的具体位置。

子组件:

<template>
  <div>
    <header>
      <slot name="header"></slot>
    </header>
    <main>
      <slot></slot> <!-- 默认插槽 -->
    </main>
    <footer>
      <slot name="footer"></slot>
    </footer>
  </div>
</template>

父组件:

<template>
  <child-component>
    <template v-slot:header>
      <h1>This is the header</h1>
    </template>
    <p>This is the main content passed to the default slot.</p>
    <template v-slot:footer>
      <p>This is the footer</p>
    </template>
  </child-component>
</template>

3. 作用域插槽

作用域插槽(Scoped Slots)允许子组件将数据传递给插槽内容。父组件可以利用这些数据来动态渲染内容。

子组件:

<template>
  <div>
    <slot :user="user"></slot>
  </div>
</template>

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

父组件:

<template>
  <child-component v-slot:default="slotProps">
    <p>User Name: {{ slotProps.user.name }}</p>
  </child-component>
</template>

子组件通过 slot 标签中的 :user="user" 将 user 对象作为插槽数据传递给父组件,父组件可以通过 slotProps.user.name 来访问并展示这个数据。

4. 动态插槽名

在 Vue 2.6+ 版本中,你可以使用动态插槽名。这允许插槽的名字是一个动态的表达式。

子组件:

<template>
  <div>
    <slot :name="dynamicSlotName"></slot>
  </div>
</template>

父组件:

<template>
  <child-component>
    <template v-slot:[dynamicSlotName]>
      <p>Dynamic content here</p>
    </template>
  </child-component>
</template>

<script>
export default {
  data() {
    return {
      dynamicSlotName: 'header'
    };
  }
};
</script>

  • 7
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Vue2插槽(slot)是一种允许我们在父组件声明内容分发到子组件的机制。它允许我们在子组件定义一些可替换的内容,在父组件使用插槽来填充这些内容。 要在Vue2使用插槽,需要在父组件使用`<slot>`标签,它表示插槽的位置。然后,在子组件使用`<slot>`标签的name属性来定义具名插槽,或者直接使用无名插槽。 下面是一个简单的例子,展示了如何使用插槽: ```html <!-- 父组件 --> <template> <div> <h1>父组件</h1> <slot></slot> </div> </template> <!-- 子组件 --> <template> <div> <h2>子组件</h2> <slot></slot> </div> </template> ``` 在这个例子,父组件的`<h1>`标签会被渲染出来,并且插槽的内容会替换掉`<slot>`标签。子组件的`<h2>`标签也会被渲染出来,并且插槽的内容会替换掉子组件的`<slot>`标签。 如果你想使用具名插槽,可以在父组件使用`<slot>`标签的name属性,然后在子组件使用具名插槽的名称来填充内容。下面是一个具名插槽的例子: ```html <!-- 父组件 --> <template> <div> <h1>父组件</h1> <slot name="content"></slot> </div> </template> <!-- 子组件 --> <template> <div> <h2>子组件</h2> <slot name="content">默认内容</slot> </div> </template> ``` 在这个例子,如果父组件没有填充具名插槽的内容,那么子组件的默认内容会被渲染出来。如果父组件填充了具名插槽的内容,那么它会替换掉子组件的`<slot>`标签。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值