Vue插槽之作用域插槽

本文详细介绍了Vue.js中作用域插槽的概念和用法,包括如何让插槽内容访问子组件的数据,以及如何在父组件中使用插槽prop。通过具体示例,展示了作用域插槽在Vue 2.6.0及更高版本中的应用。

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

Vue官方文档

Vue在2.6.0版本以后对作用域插槽的语法做了修改。现总结一下
作用域插槽:让插槽内容能够访问子组件中才有的数据
有一个带有如下模板的 <current-user> 组件

<span>
  <slot>{{ userInfo.lastName }}</slot>
</span>

我们想让它的后备内容显示用户的名,以取代正常情况下用户的姓,如下:

<current-user>
  {{ userInfo.firstName }}
</current-user>

因为userInfo是<current-user> 组件中的数据。父组件访问不到。所以以上代码不能够运行。
为了让 userInfo在父级的插槽内容可用,我们可以将 userInfo作为一个 <slot> 元素的特性绑定上去

<span>
  <slot v-bind:userInfo="userInfo">
    {{ userInfo.lastName }}
  </slot>
</span

绑定在 <slot> 元素上的特性被称为插槽 prop。现在在父级作用域中,我们可以给 v-slot 带一个值来定义我们提供的插槽 prop 的名字

<current-user>
  <template v-slot:default="slotProps">
    {{ slotProps.userInfo.firstName }}
  </template>
</current-user>

在这个例子中,我们选择将包含所有插槽 prop的对象命名为 slotProps,但你也可以使用任意你喜欢的名字。
完整代码如下:
父组件代码:App.vue

<template>
  <div id="app">
    <current-user>
      <template v-slot:default="slotProps">{{slotProps.userInfo.lastName}}</template>
      //可以简写为
      //<template v-slot:default="{userInfo}">{{userInfo.lastName}}</template>
    </current-user>
  </div>
</template>

<script>
  import CurrentUser from "./components/CurrentUser";
  export default {
    name: 'App',
    components: {CurrentUser}
  }
</script>

子组件代码:CurrentUser.vue

<template>
  <span>
    <slot v-bind:userInfo="userInfo">{{userInfo.firstName}}</slot>
  </span>
</template>

<script>
  export default {
    name: "CurrentUser",
    data(){
      return{
        userInfo:{
          firstName:'风',
          lastName:'清扬'
        }
      }
    }
  }
</script>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值