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

被折叠的 条评论
为什么被折叠?



