【无标题】

本文详细介绍了Vue.js中的插槽用法,包括默认插槽、具名插槽和作用域插槽。默认插槽用于替换子组件内部的内容,具名插槽通过name属性指定替换区域,作用域插槽允许父组件访问子组件的数据,实现数据传递。示例代码展示了如何在父组件模板中使用这些插槽,以及子组件如何定义它们。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

插槽基本使用

父组件

index.vue

<son1>
  <template>
    I'm content
  </template>
</son1>

components: {
    son1: () => import('./son1.vue'),
}

子组件

son1.vue

<div>
  <!-- 定义插槽 -->
  <!-- 定义可以用来被替换的结构 -->
  <slot>内容</slot>
</div>
<div>底部</div>

具名插槽

  • 插槽有一个name属性
父组件

index.vue

<son2>
  <!-- 简写形式 vant -->
  <template #content>I'm content</template>
  <template #foot>I'm foot</template>

  <!-- 原始形式 -->
  <template v-slot:content>I'm content</template>
  <template v-slot:foot>I'm foot</template>

  <!-- 被废弃的用法:element -->
  <template slot="content">我是内容</template>
  <template slot="foot">我是底部</template>
</son2>

components: {
    son2: () => import('./son2.vue'),
}
子组件

son2.vue

<div>
  <!-- 定义插槽 -->
  <!-- 定义可以用来被替换的结构 -->
  <slot name="content">内容</slot>
</div>
<div>
  <slot name="foot">底部</slot>
</div>

匿名插槽

  • 又叫默认插槽,单个插槽
  • 它不需要设置name属性,它隐藏的name属性为default
父组件

index.vue

<son3>
  <template slot="content">我是内容</template>
  <template slot="foot">我是底部</template>
  <template #default>
    我是头部的默认插槽
  </template>
</son3>

components: {
    son3: () => import('./son3.vue'),
}
子组件

son3.vue

<div>
  <!-- 没有 name 属性的插槽叫做默认插槽 -->
  <slot>头部</slot>
</div>
<div>
  <slot name="content">内容</slot>
</div>
<div>
  <slot name="foot">底部</slot>
</div>

作用域插槽

作用域插槽其实就是可以传递数据的插槽。子组件中的一些数据想在父组件中使用,必须通过规定的方法来传递。在官方文档中提出了一条规则,**父级模板里的所有内容都是在父级作用域中编译的。子模板里的所有内容都是在子作用域中编译的。**如果你在父组件直接使用子组件中的值,是会报错的。

父组件

index.vue

    <son4>
      <!-- 给每本书添加一个 《》 -->
      <!-- 简写形式: vant -->
      <template #content="{list,a}">
        <ol>
          <li v-for="(item, index) in list" :key="index">
            《{{ item.name }}》
          </li>
        </ol>
      </template> 

      <!-- 原始形式 -->
      <template v-slot:content="{list}">
        <ol>
          <li v-for="(item, index) in list" :key="index">
            《{{ item.name }}》
          </li>
        </ol>
      </template>

	  <!-- element中被废弃的写法 -->
      <template slot="content" slot-scope="{ list, a }">
        <ol>
          <li v-for="(item, index) in list" :key="index">
            《{{ item.name }}》
          </li>
        </ol>
        <div>a:{{ a }}</div>
      </template>
    </son4>
子组件

son4.vue

<div>
  <slot name="content" :list="list" a="a">
    <ol>
      <li v-for="(item, index) in list" :key="index">
        {{ item.name }}
      </li>
    </ol>
  </slot>
</div>

data () {
  return {
    list: [
      { id: 1, name: '三国演义' },
      { id: 2, name: '红楼梦' },
      { id: 3, name: '西游记' },
      { id: 4, name: '水浒传' }
    ]
  }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值