Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

vue slot

作者:苏染瞳°   发布日期:2025-03-08   浏览:108

<template>
  <div>
    <!-- 定义一个包含具名插槽和作用域插槽的组件 -->
    <slot-component>
      <!-- 默认插槽内容 -->
      <template #default>
        <p>这是默认插槽的内容</p>
      </template>

      <!-- 具名插槽内容 -->
      <template #header>
        <h1>这是具名插槽 header 的内容</h1>
      </template>

      <!-- 作用域插槽内容 -->
      <template #item="scope">
        <p>这是作用域插槽 item 的内容,数据为:{{ scope.itemData }}</p>
      </template>
    </slot-component>
  </div>
</template>

<script>
export default {
  name: 'App'
}
</script>

<!-- slot-component.vue 文件内容如下 -->
<template>
  <div>
    <!-- 默认插槽 -->
    <slot></slot>

    <!-- 具名插槽 -->
    <header>
      <slot name="header"></slot>
    </header>

    <!-- 作用域插槽 -->
    <ul>
      <li v-for="item in items" :key="item.id">
        <slot name="item" :itemData="item"></slot>
      </li>
    </ul>
  </div>
</template>

<script>
export default {
  name: 'SlotComponent',
  data() {
    return {
      items: [
        { id: 1, name: 'Item 1' },
        { id: 2, name: 'Item 2' },
        { id: 3, name: 'Item 3' }
      ]
    }
  }
}
</script>

解释说明:

  1. 默认插槽

    • 在父组件中使用 <template #default> 来定义默认插槽的内容。
    • 子组件中使用 <slot></slot> 来定义默认插槽的位置。
  2. 具名插槽

    • 在父组件中使用 <template #header> 来定义具名插槽的内容。
    • 子组件中使用 <slot name="header"></slot> 来定义具名插槽的位置。
  3. 作用域插槽

    • 在父组件中使用 <template #item="scope"> 来定义作用域插槽的内容,并通过 scope 接收子组件传递的数据。
    • 子组件中使用 <slot name="item" :itemData="item"></slot> 来传递数据给父组件的作用域插槽。

上一篇:vue table

下一篇:vue路由

大家都在看

vue.config.js configu

node.js vue

vue查看版本

vue等待几秒

vue3 setup computed

vue screenfull

vue json.stringify

vue 遍历list

typescript vue

vue 复选框

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站