天天看点

Vue插槽之作用域插槽

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>